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?

Answers:

Answer

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.)

Answer
var dateString ='23/06/2015';
var splitDate = dateString.split('/');
var month = splitDate[1] - 1; //Javascript months are 0-11

var date = new Date(splitDate[2], month, splitDate[0]);
Answer
  • Split the date into day, month, year parts using dateSet.split('/')
  • Pass these parts in the right order to the Date constructor.
Answer

Yes, there is problem with the date format you are using. If you are not setting a date format the default date that is used is 'mm/dd/yy. So you should set your preferred date formate when you create it as following when you create the date picker:

$(".selector" ).datepicker({ dateFormat: 'dd/mm/yyyy' });

or you can set it later as:

$.datepicker.formatDate('dd/mm/yyyy');
Answer

When you try to create a date object:

new Date(year, month, day, hours, minutes, seconds, milliseconds)

Example:

dateSetD = new Date(dateSet.year, dateSet.month, dateSet.day);

Note: JavaScript Date object's month starts with 00, so you need to adjust your dateset accordingly.

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.