6

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

jQuerybeast
  • 14,130
  • 38
  • 118
  • 196

2 Answers2

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());
mplungjan
  • 169,008
  • 28
  • 173
  • 236
kennebec
  • 102,654
  • 32
  • 106
  • 127
  • 1
    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;` – Crickets May 09 '19 at 05:00
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();
Tom
  • 8,509
  • 7
  • 49
  • 78
  • 1
    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(); ? – jQuerybeast Jul 27 '11 at 00:43
  • 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. – Tom Jul 27 '11 at 22:16
  • 1
    `getMonth()` will return 0 – Menai Ala Eddine - Aladdin Apr 24 '20 at 01:43
  • 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. – Tom Apr 24 '20 at 14:33