33

I have a date in this format: dd.mm.yyyy

When I instantiate a JavaScript date with it, it gives me a NaN

In c# I can specify a date format, to say: here you have my string, it's in this format, please make a Datetime of it.

Is this possible in JavaScript too? If not, is there an easy way?

I would prefer not to use a substring for day, substring for month etc. because my method must also be capable of german, italian, english etc. dates.

7 Answers 7

58

You will need to create a function to extract the date parts and use them with the Date constructor.

Note that this constructor treats months as zero based numbers (0=Jan, 1=Feb, ..., 11=Dec).

For example:

function parseDate(input) { var parts = input.match(/(\d+)/g); // note parts[1]-1 return new Date(parts[2], parts[1]-1, parts[0]); } parseDate('31.05.2010'); // Mon May 31 2010 00:00:00 

Edit: For handling a variable format you could do something like this:

function parseDate(input, format) { format = format || 'yyyy-mm-dd'; // default format var parts = input.match(/(\d+)/g), i = 0, fmt = {}; // extract date-part indexes from the format format.replace(/(yyyy|dd|mm)/g, function(part) { fmt[part] = i++; }); return new Date(parts[fmt['yyyy']], parts[fmt['mm']]-1, parts[fmt['dd']]); } parseDate('05.31.2010', 'mm.dd.yyyy'); parseDate('31.05.2010', 'dd.mm.yyyy'); parseDate('2010-05-31'); 

The above function accepts a format parameter, that should include the yyyy mm and dd placeholders, the separators are not really important, since only digits are captured by the RegExp.

You might also give a look to DateJS, a small library that makes date parsing painless...

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

3 Comments

i would like to process the mm/dd/yyyy and dd/mm/yyyy too
Excellent! works like a charm! hate it though that i have no clue how it works :)
Powerfull! DateJs is grate.
19

It's easy enough to split the string into an array and pass the parts directly to the Date object:

var str = "01.01.2010"; var dmy = str.split("."); var d = new Date(dmy[2], dmy[1] - 1, dmy[0]); 

1 Comment

Date()'s month parameter takes Month in Zero based index. January = 0, february = 1, march = 2... etc
12

There is no built in way to manipulate dates the way you would like.

The jQuery-UI datepicker has the functionality you want, I'm sure many other libraries have something similar.

$.datepicker.parseDate('dd.mm.yy', '31.12.2007'); 

5 Comments

yeay, this is something i want, but without the whole datepicker lib if possible. So i would like one of those 'may other libraries' :-)
@Michel check out "datejs", which is used by the jQuery UI datepicker
@Pointy - perfect, I was just finding the same thing
Datejs has been 'abandoned' since 2008 according to this StackOverFlow page. It has been forked so you could try that or use Moment.
Building on @Ben's point, Moment has a way to create a date based on a specific string format
1
t="01.01.1970" parts = t.split("."); for(var i = 0; i < parts.length; i++) parts[i] = parseInt(parts[i], 10); new Date(parts[2], parts[1]-1, parts[0]); 

Date defined as (Year, Month, Date)
Date()'s month parameter takes Month in Zero based index. January = 0, february = 1, march = 2... etc

Parsing the string to an int isn't necessary, but I dislike passing strings into functions and just hoping that JavaScript will "get it"... Sort of like how some people prefer ===

2 Comments

parseInt shouldn't be required (JavaScript's typing is dynamic and strings should automatically be cast to a number) and the loop is a bit OTT for such a simple operation.
What @Andy says is that the Date constructor will explicitly convert the arguments internally ToNumber. Also, using parseInt without the radix argument, is specially harmful here, since you can have a date like "09.09.2010", and parseInt('09') == 0, since the preceding zero will force the number conversion as octal base, and this doesn't happen with the internal ToNumber operation.
1

Building on CMS answer, I created this function to deal with a variable format

function parseDate(input, format) { format = format || 'yyyy-mm-dd'; // default format //Change from PHP date format to JS if (format == 'd/m/Y') { format = 'dd/mm/yyyy'; } if (format == 'd/m/Y H:i:s') { format = 'dd/mm/yyyy hh:ii:ss'; } let date = NaN; if (format == 'dd/mm/yyyy') { let parts = input.match(/(\d+)/g), i = 0, fmt = {}; // extract date-part indexes from the format format.replace(/(yyyy|dd|mm)/g, function(part) { fmt[part] = parts[i++]; }); //create date for new format let createdDate = new Date(fmt['yyyy'], fmt['mm']-1, fmt['dd']); //check if dates are equal by comparing parts. The issue I had here was //when I passed an invalid value for month, the output was adjustement to //accomodate for the extra months if ( createdDate.getFullYear() == fmt['yyyy'] && createdDate.getMonth() == (fmt['mm']-1) && createdDate.getDate() == fmt['dd'] ) { date = createdDate; } } //same but taking into account hours minute and seccond if (format == 'dd/mm/yyyy hh:ii:ss') { let parts = input.match(/(\d+)/g), i = 0, fmt = {}; // extract date-part indexes from the format format.replace(/(yyyy|dd|mm|hh|ii|ss)/g, function(part) { fmt[part] = parts[i++]; }); let createdDate = new Date( fmt['yyyy'], fmt['mm']-1, fmt['dd'], fmt['hh'], fmt['ii'], fmt['ss'] ); if ( createdDate.getFullYear() == fmt['yyyy'] && createdDate.getMonth() == (fmt['mm']-1) && createdDate.getDate() == fmt['dd'] && createdDate.getHours() == fmt['hh'] && createdDate.getMinutes() == fmt['ii'] && createdDate.getSeconds() == fmt['ss'] ) { date = createdDate; } } return date; } 

Comments

1

Update Oct 2023

As per Documentation:

moment(...) is local mode. Ambiguous input (without offset) is assumed to be local time. Unambiguous input (with offset) is adjusted to local time.

So it is better to always specify a timezone:

let myDateVanilla = new Date("08.06.2023"); console.log(myDateVanilla); //"2023-08-05T22:00:00.000Z" -> Not correct let myDateMoment = moment.tz("08.06.2023", "DD.MM.YYYY", "America/Los_Angeles").toDate(); console.log(myDateMoment); //"2023-06-07T22:00:00.000Z"-> Correct
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.43/moment-timezone-with-data.js"></script>

Also beware of the difference of these two lines:

moment.tz(date, format, timezone) moment(date, format).tz(timezone) 

The first one get the date in the timezone specified as parameter, the second one assumes the timezone from the browser and converts it to the timezone passed as parameter.

Previous Answer

You can use MomentJs in the following way. The example tries to convert the 8th Jun 2023

let myDateVanilla = new Date("08.06.2023"); console.log(myDateVanilla); //"2023-08-05T22:00:00.000Z" -> Not correct let myDateMoment = moment("08.06.2023", "DD.MM.YYYY").toDate(); console.log(myDateMoment); //"2023-06-07T22:00:00.000Z"-> Correct
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

Please bewhare of the ouput, you may see a different day than the 8th Jun 2023 because of timezone

Comments

0

Modified version of the accepted answer which supports value and format without 'dd' and uppercase format

function parseDate(input, format) { format = (format || 'yyyy-mm-dd').toLowerCase(); // default format var parts = input.match(/(\d+)/g), i = 0, fmt = {}; // extract date-part indexes from the format format.replace(/(yyyy|dd|mm)/g, function(part) { fmt[part] = i++; }); return new Date([parts[fmt['yyyy']], parts[fmt['mm']], parts[fmt['dd']]].filter(x => x !== undefined).join('-')); } parseDate('10/2018', 'MM/YYYY') 

1 Comment

Hi welcome to Stack Overflow and thank you for your answer. While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.