0

I am using Javascript Date object toString method to format the date as follows

var firstDate ='13/11/2015 13:27:24';
var secondDate ='07/11/2015 13:19:45';

var dateDisplay1 =  Date.parse(firstDate).toString("dd/MM/yyyy  HH:mm");

OUTPUT : 13/11/2015 13:27 =>November 13th is correct

var dateDisplay2 =  Date.parse(secondDate ).toString("dd/MM/yyyy  HH:mm");
11/07/2015 13:19

OUTPUT : 11/07/2015 13:19 =>July 11th is wrong it should be Nov 7th

EXPECTED for dateDisplay2 will be 07/11/2015 13:19

5
  • 1
    The default is American date format, use this to declare date Date("2015-11-7") or Date("7 Nov 2015") Commented Dec 2, 2015 at 5:22
  • 2
    Do not parse strings using Date.parse, ever. Parse them manually. A library can help, but you must know the format beforehand and if you only need to deal with one, then two lines are all that's required. Commented Dec 2, 2015 at 5:24
  • I get NaN when I try your code, even for the 1st one: jsfiddle.net/gratiafide/kgstubtn/9 I think you are going to need to use "split()" and create a new Date object from that. Commented Dec 2, 2015 at 5:32
  • Something like moment.js is good for parsing dates, including locale support, if you're able to use a library. Commented Dec 2, 2015 at 5:41
  • Check out this edit. jsfiddle.net/kgstubtn/14 Commented Dec 2, 2015 at 5:45

4 Answers 4

2

UPDATED

Here is one way to do it manually:

http://jsfiddle.net/gratiafide/kgstubtn/18/

Javascript:

var firstDate = '13/11/2015 13:27:24';
var secondDate = '07/11/2015 13:19:45';

document.getElementById("myBtn").addEventListener("click", function () {
  var splitHalf = firstDate.split(" ");
  var splitCalendar = splitHalf[0].split("/");
  var splitMinutes = splitHalf[1].split(":");
  var date = splitCalendar[0] + "/" + splitCalendar[1] + "/" + splitCalendar[2] + " " + splitMinutes[0]  + ":" + splitMinutes[1];
  document.getElementById("demo").innerHTML = date;
});

HTML:

<p>Click the button to display your date formatted correctly.</p>

<button id="myBtn">Try it</button>

<p id="demo"></p>
Sign up to request clarification or add additional context in comments.

2 Comments

Gets my vote for thinking outside the box. But you could just trim the seconds and be done with it: date.replace(/:\d\d$/,''). ;-)
Good point and thanks for the vote. Doing it like this gives you more options if you'd like to change the format in the future.
2

var dateDisplay1 = Date.parse(firstDate).toString("dd/MM/yyyy HH:mm");

There are a few issues here.

Parsing of date strings is largely implementation dependent, and where following standards, may produce inconsistent results. You should manually parse date strings, a library can help but a 2 line function will suffice if you only have one format and are sure it's a valid date (see below). To test for a valid date is only one extra line.

Date.parse returns a number, which is a time value, so Date.parse(...).toString() is calling Number.prototype.toString where the passed argument is a radix. So if Date.parse returns a suitable value, then:

new Date(Date.parse(...)).toString()

would be required.

If you wish to present the date string in a particular format, you can test for support for the internationalization API and use that and fall back to your own function (or just use your own), e.g.

function parseDMY(s) {
  var b = s.split(/\D+/);
  return new Date(b[2], b[1]-1, b[0], b[3], b[4], b[5]);
}

function formatDateDMYhm(d) {

  // Use internationalization API if available
  if (typeof Intl == 'object' && typeof Intl.DateTimeFormat == 'function') {
    options = {
      year: 'numeric', month: '2-digit', day: '2-digit',
      hour: '2-digit', minute: '2-digit', /* second: '2-digit', */
      hour12: false
    };
    return d.toLocaleString('en-GB', options);
  }

  // Otherwise, use bespoke function    
  function z(n){return (n<10? '0':'') + n}
  return z(d.getDate()) + '/' + z(d.getMonth()) + '/' + d.getFullYear() +
         ' ' + z(d.getHours()) + ':' + z(d.getMinutes());
}

var firstDate ='13/11/2015 13:27:24';
var secondDate ='07/11/2015 13:19:45';

document.write(formatDateDMYhm(parseDMY(firstDate)) + '<br>');
document.write(formatDateDMYhm(parseDMY(secondDate)));

Though if the internationalisation API is used, it inserts an extra comma after the date in some browsers (e.g. Chrome) but not others (e.g. IE), so even using standards does not necessarily produce a "standard" result. Maybe it shouldn't be used in this case. Using the month name is much less ambiguous, so consider using that instead, e.g. 13-Nov-2015 13:27.

1 Comment

Ah your answer was very similar! :) +1 back at ya
1

There is a space after secondDate. Remove it.

var dateDisplay2 =  Date.parse(secondDate).toString("dd/MM/yyyy  HH:mm");

1 Comment

No, don't do that. Date.parse is not required by any standard to correctly parse the string in the OP. Also, it returns a number, not a Date so you are calling Number.prototype.toString. No ECMA-262 standard requires the toString method take any arguments, it is entirely implementation dependent so the argument is most probably ignored.
-1

Simply use new Date(string) and pass date string.

Thanks

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.