0

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?

2

2 Answers 2

2

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.

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

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.