0

I currently have two variables:

appointment_date and appointment_time which are in the format dd/mm/yyyy and (h)h:mm respectively.

The time is 12 hour format but for times before 12PM there is no zero padding as I am grabbing these values from the DOM and this is how it is presented.

I am trying to compare the current date and time with these two values to calculate if the time difference is less than 24 hours which I am able to do with the following hard-coded date objects:

var todays_date = new Date(2013, 04, 19, 15, 40, 0);
var appointment_date = new Date(2013, 04, 20, 15, 30, 0);

todays_date = todays_date.getTime();
appointment_date = appointment_date.getTime();

if ((appointment_date - todays_date) >  86400000) { // number of milliseconds in a day
    // proceed 
} else {
    alert('less than 24 hours');
}

I can make a date time object from today's date by doing

var todays_date = new Date();

but I don't know the best way to create a new date object from appointment_date and appointment_time, bearing in mind that certain times will need to be zero padded as well.

I considered trying to replace the / in the date with , and the : in time with a , and joining the two with a , in between but I was hoping that were would be a more elegant solution?

6
  • This might be very handy for you: momentjs.com Commented May 9, 2013 at 8:48
  • What you considered wouldn't work. The Date constructor you're using in your hard coded example has individual number arguments being passed to it; whereas you'd be passing a single argument - a string - that happens to look kind of like the argument list if you were using it properly. Commented May 9, 2013 at 8:48
  • Side note: Avoid leading zeros on number literals, e.g. don't write 04, write 4. Some implementations, in non-strict mode, will treat a number literal starting with a zero as octal rather than decimal. Commented May 9, 2013 at 8:49
  • my rule of thumb with dates is always use epoch times in the code. use formatted dates only for output Commented May 9, 2013 at 8:56
  • thanks T.J, Anthony and Dave. Commented May 9, 2013 at 8:56

1 Answer 1

4

Just split the appointment_date string into its three parts (split('/'), for instance), convert those parts to numbers, do the same with the appointment_time (split(':')), remember to subtract one from the month value (months are zero-based), and pass those numbers into the Date constructor.

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

Comments

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.