Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript date objects UK dates

I have the following code

 datePicker.change(function(){
        dateSet = datePicker.val();
        dateMinimum = dateChange();
        dateSetD = new Date(dateSet);
        dateMinimumD = new Date(dateMinimum);
        if(dateSetD<dateMinimumD){
            datePicker.val(dateMinimum);
            alert('You can not amend down due dates');
        }       
    })

dateSet = "01/07/2010" dateMinimum = "23/7/2010"

Both are UK format. When the date objects are compared dateSetD should be less than dateMinimumD but it is not. I think it is to do with the facts I am using UK dates dd/mm/yyyy. What would I need to change to get this working?

like image 677
Linda Avatar asked Jun 25 '10 10:06

Linda


People also ask

How does JavaScript store dates in objects of date type?

JavaScript Stores Dates as Milliseconds JavaScript stores dates as number of milliseconds since January 01, 1970. Zero time is January 01, 1970 00:00:00 UTC. One day (24 hours) is 86 400 000 milliseconds.

Which JavaScript object works with the dates?

The Date Object. The Date object is a built-in object in JavaScript that stores the date and time. It provides a number of built-in methods for formatting and managing that data.

What timezone does JavaScript date use?

JavaScript's internal representation uses the “universal” UTC time but by the time the date/time is displayed, it has probably been localized per the timezone settings on the user's computer.

What date format is dd mm yyyy in JavaScript?

To format a date as dd/mm/yyyy:Use the getDate() , getMonth() and getFullYear() methods to get the day, month and year of the date. Add a leading zero to the day and month digits if the value is less than 10 .


2 Answers

The JavaScript Date constructor doesn't parse strings in that form (whether in UK or U.S. format). See the spec for details, but you can construct the dates part by part:

new Date(year, month, day);

MomentJS might be useful for dealing with dates flexibly. (This answer previously linked to this lib, but it's not been maintained in a long time.)

like image 90
T.J. Crowder Avatar answered Oct 03 '22 12:10

T.J. Crowder


This is how I ended up doing it:

 var lastRunDateString ='05/04/2012'; \\5th april 2012
 var lastRunDate = new Date(lastRunDateString.split('/')[2], lastRunDateString.split('/')[1] - 1, lastRunDateString.split('/')[0]);

Note the month indexing is from 0-11.

like image 38
woggles Avatar answered Oct 03 '22 12:10

woggles