user1371896
user1371896

Reputation: 2240

using date function javascript

I am trying to change the format of a date from one to another, for exmple 10/05/2012 14:30:56 to 10th May 2012 12:30:56

The javascript function that Ive used is

var monthNames = new Array("January", "February", "March","April", "May", "June", "July", "August", "September", "October", "November", "December");



var today = new Date("10/05/2012 14:30:56");
var cDate = today.getDate();
var cMonth = today.getMonth();
var cYear = today.getFullYear();
var cHour = today.getHours();
var cMin = today.getMinutes();
var cSec = today.getSeconds();
alert( monthNames[cMonth] + " " +cDate  + "," +cYear + " " +cHour+ ":" + cMin+ ":" +cSec );

The output the I get is October 5th which is incorrect. So how do I interchange the date and month?

Upvotes: 0

Views: 391

Answers (2)

kennebec
kennebec

Reputation: 104810

It can be handy to know the default string for Dates on the user, for formatting and setting up inputs. You only need to check once per session:

Date.ddmm: (function(){
    return Date.parse('2/6/2009')==1243915200000;
})();

if(Date.ddmm)//format DD/MM/YYYY;
else ////format MM/DD/YYYY;

Upvotes: 0

Wladimir Palant
Wladimir Palant

Reputation: 57681

The Date constructor assumes American date format - meaning MM/DD/YYYY. If you want to use the British date format (DD/MM/YYYY) you will have to exchange day and month manually, like this:

var date = "10/05/2012 14:30:56";
if (/^(\d+)\/(\d+)(.*)/.test(date))
  date = RegExp.$2 + "/" + RegExp.$1 + RegExp.$3;

var today = new Date(date);

Then you can perform your usual date conversion.

Upvotes: 2

Related Questions