Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set new Date() with a string containing a date in UK format

I want to be able to enter a UK formatted date when creating a new Date from a string, that will work in all modern browsers, but mainly FireFox and IE.

new Date('24/06/2014') // Gives 06/24/2014

Because I want to set a jquery datepicker using it.

Is it possible to get

new Date()

to interpret a UK date passed as a string?

new Date('24/06/2014').toLocaleString("en-GB") // Gives 06/12/2015

new Date('06/24/2014').toLocaleString("en-GB") // Gives 24/06/2014

The real problem is when I use the datepicker I specify UK date format and everything is fine...

$("#outOfStockFromDate").datepicker({
    dateFormat: 'dd/mm/yy',
changeMonth: true,
numberOfMonths: 3,
onClose: function (selectedDate) {
    $("#to").datepicker("option", "minDate", selectedDate);
}});

Until I try to repopulate the datepicker using this UK date format using something like...

$("#outOfStockFromDate").datepicker("setDate", testDate);

It's as if the string 'testDate' must be in US format... grrr

EDIT: I realise there are two parts to this question, the first part dealing with datepicker; it was my stupid fault that I was initialising it at the same time I was trying to setDate (this error led me down the Date() route). Now I have it initialised and changed correctly it accepts UK format dates!

Second part yes the date functionality in javascript regarding formatting dates (now I know) is famously lacking... but as I've solved my initial problem I don't care about this one... P.S. I ended up splitting and reconstructing the date in US Date Format (in a string) then using new Date(USDateFormattedString).... and then I realised!

So to end, essentially my code was correct in it's syntax, but in it's execution it was not.

Thanks to everyone who answered! +1

like image 482
Paul Zahra Avatar asked Dec 03 '25 01:12

Paul Zahra


1 Answers

You can't get new Date to accept a string with a date in UK format directly, however, you can parse it manually as I've shown in another question with similar issue:

function parseDMY(value) {
    var date = value.split("/");
    var d = parseInt(date[0], 10),
        m = parseInt(date[1], 10),
        y = parseInt(date[2], 10);
    return new Date(y, m - 1, d);
}

This version as is accepts dates like this one:

parseDMY("01/13/2014").toLocaleString("en-GB")
"1/1/2015 00:00:00"

You can add some validations if you want to make sure that doesn't happen.

like image 197
izstas Avatar answered Dec 05 '25 17:12

izstas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!