0

I need to validate time picked by user, start date must be greater than 6 am and smaller than end date which must not exceed next day 2 am.

though I dont have date as an input I assume I should append dates to the picked times to compare, is this the best way to achieve it or there is a smarter one ?

here is what I can think of so far

function compareTimes(start,end){
    var t1 = new date();
    var t2 = new date();

    var starttime = t1 + " " + start;
    if (end >= '00:00'){
        t2.setDate(t2.getDate()+1);
    } 
    var endtime = t2 + " " + end;
    if(Date.parse ( endtime ) > Date.parse ( starttime )){
        alert ("greater than");
        return true
    }
}
3
  • 1
    show us the code you tried Commented Feb 21, 2013 at 15:53
  • What’s in the start and end parameters? It looks to be a string, formatted as HH:nn, but is it guaranteed to be that? Commented Feb 21, 2013 at 16:59
  • @Martijn yes exactly as you said Commented Feb 21, 2013 at 17:07

2 Answers 2

1

Try this library. Differency function should work for you. http://momentjs.com

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for your answer, but I'll have to void libraries (the page is already loaded)
@Digitalfortress: I take it you mean to avoid libraries... :-) But what does it matter whether the page is already loaded? You can add the library, and reload the page, no?
Sorry for the typo :) Well, this is the clients' opinion!!
@Digitalfortress: Wait, what? The client decides what libraries you get to use, and which libraries you don’t?
0

The following function appends a time string like the one you give, to a date, and returns that as a new Date object. If you pass no date, it will use today’s date.

function setDateTime(timeString, date) {
    var result = (date ? new Date(date) : new Date())
    ,   match = /(\d+):(\d+)/.exec(timeString)
    ;
    result.setHours(Number(match[1]), Number(match[2]), 0, 0);
    return result;
}

Once you’ve got your startDate = setDateTime(start); and your endDate = setDateTime(end);, you can then use the getHours method to figure out if it’s before or after 2 am or 6 pm.

N.B. you should probably check if the hour < 6, and it so, add a day to it (endDate.setDate(endDate.getDate() + 1);, otherwise your end date will be before your start date. :-)

1 Comment

Thanks a lot, thats what I had in mind but didnt know how to implement it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.