7

I am trying to get the LocaleDateString and the LocaleTimeString which that would be toLocaleString() but LocaleString gives you GMT+0100 (GMT Daylight Time) which I wouldn't it to be shown.

Can I use something like:

timestamp = (new Date()).toLocaleDateString()+toLocaleTimeString();

Thanks alot

2
  • If its possible I can do this, why would I format it? Thanks Commented Jul 27, 2011 at 0:35
  • 2
    Oh, then "how do I format a javascript date" would be a better subject. kennebec has your answer. :-) Commented Jul 28, 2011 at 4:03

2 Answers 2

18

You can use the local date string as is, just fiddle the hours, minutes and seconds.

This example pads single digits with leading 0's and adjusts the hours for am/pm.

function timenow() {
  var now = new Date(),
    ampm = 'am',
    h = now.getHours(),
    m = now.getMinutes(),
    s = now.getSeconds();
  if (h >= 12) {
    if (h > 12) h -= 12;
    ampm = 'pm';
  }

  if (m < 10) m = '0' + m;
  if (s < 10) s = '0' + s;
  return now.toLocaleDateString() + ' ' + h + ':' + m + ':' + s + ' ' + ampm;
}
console.log(timenow());

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

1 Comment

Note: this answer will display 0:30:00 am instead of 12:30:00 am. To fix this, add: else if(h==0) h = 12;
9

If you build up the string using vanilla methods, it will do locale (and TZ) conversion automatically.

E.g.

var dNow = new Date();
var s = ( dNow.getMonth() + 1 ) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();

4 Comments

Thanks sir. I would rather get the date as UK or US depends on the user. So instead of 6/27/2011 they could use it as 27/6/2011 so would you recommend dNow.toLocaleDateString() + ' ' + dNow.getHours() + ':' + dNow.getMinutes(); ?
In that case, start with a straight-up toLocaleString() call, and do regex replacement on the results to either remove the unwanted components or isolate the desired ones.
getMonth() will return 0
I think my answer is not great, and the "+ 1" edit doesn't change that. One of the main reasons for using locale-aware methods is precisely that different locales use different orderings of the date parts. The technique I use here defeats that completely. The accepted answer has similar weaknesses. I'm no longer sure I even know precisely what OP is asking for, but I think both answers here are very definitely wrong.

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.