12

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?

Linda
  • 2,227
  • 5
  • 30
  • 40

6 Answers6

14

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
13

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.

woggles
  • 7,444
  • 12
  • 70
  • 130
11
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]);
5
  • Split the date into day, month, year parts using dateSet.split('/')
  • Pass these parts in the right order to the Date constructor.
Sjoerd
  • 74,049
  • 16
  • 131
  • 175
0

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');
Thea
  • 7,879
  • 6
  • 28
  • 40
0

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.

piyer
  • 746
  • 4
  • 11
  • JavaScript doesn't have Python-style keyword arguments. What you're doing in the example is assigning `dateSet.year` to an accidental global variable `year`! – bobince Jun 25 '10 at 11:08