tags:

views:

105

answers:

3

How can I convert European format date to USA in JavaScript?

Here is an example:

30.01.2010 -> European 
2010-01-30 -> USA

Meaning convert d.m.Y to Y-m-d. I know how to do this in PHP but I need it in JavaScript.

+3  A: 

Datejs can parse that. The code is at http://datejs.googlecode.com/files/date.js

EDIT: It is not safe to left date.js determine the format string automatically. I made the mistake of not testing with a day <= 12 (duh). You should use:

Date.parseExact('09.01.2010', 'd.M.yyyy').toString('yyyy-MM-dd');

or

Date.parseExact('09.01.2010', 'dd.MM.yyyy').toString('yyyy-MM-dd');

depending on whether you want to allow single digit days.

Matthew Flaschen
We use date.js for our app, and it has different localised files to format or parse de date depending on local settings. If you take the US format(mm/dd) and enter the date in European format(dd/mm), date.js will not understand it right. You need to load the correct file if you want it to work properly.
Mic
Mic, thank you for the heads-up. I retested, and my original code actually works (on all inputs) on en-GB, but not en-US (even though I was using en-US to test). @c0mrade, make sure you use the above fix.
Matthew Flaschen
+1  A: 

Datejs is a bit bloated if you only need to do this. You can use split() and concatenate the results:

var eu_date = '30.01.2010';
var parts = eu_date.split('.');
var us_date = parts[2]+'-'+parts[1]+'-'+parts[0];

For these kinds of conversions where no date logic is needed, it's usually smartest to just use string manipulation tools.

Tatu Ulmanen
Yes, but it might be nice to know whether the European date is valid (depending on where it's coming from).
Matthew Flaschen
+6  A: 

You can do this pretty simply. Just split the european date into an array, reverse it, and then join it with dashes.

var euro_date = '30.01.2010';
euro_date = euro_date.split('.');
var us_date = euro_date.reverse().join('-');
ashrewdmint