Converting Australian (little endian) date to ISO using just one line in PHP or Javascript

|
Working with dates can often be problematic when dealing with Australian localization (dd/mm/yyyy, little endian) as most server software tends to understand either ISO based (yyyy-mm-dd, big endian) formats or US formats (mm/dd/yyyy, middle endian). Having seen various solutions that involve regular expressions or reconstruction of date strings using string concatenation I realized there is a much simpler way to go from Australian dates to ISO dates that MySQL and PHP's strtotime will happily work with.

In PHP the code is:

// Original: '31-12-2008'
// $isoDate: '2008-12-31'
$isoDate = join('-', array_reverse(split('-', '31-12-2008')));


In Javascript the code is:

// Original: '31-12-2008'
// isoDate: '2008-12-31'
var isoDate = '31-12-2008'.split('-').reverse().join('-');


The above one liners can be expanded to turn the given Australian dates into usable time with just a little bit more code as well.

In PHP the code is:

$t = strtotime(join('-', array_reverse(split('-', '31-12-2008'))));


In Javascript the code is:

var t = new Date('31-12-2008'.split('-').reverse().join(''));


Looking at the above code it appears that it is actually easier to turn a little endian date into an ISO date than it is to covert a middle endian date into an ISO date as the array reverse trick will not be applicable when a flip is required between the first and second date elements. In such cases regular expressions would do the trick much more nicely.

0 comments:

Post a Comment