Get local Date string and time string
Asked Answered
D

2

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

Deviled answered 27/7, 2011 at 0:27 Comment(2)
If its possible I can do this, why would I format it? ThanksDeviled
Oh, then "how do I format a javascript date" would be a better subject. kennebec has your answer. :-)Bedelia
C
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());
Caulescent answered 27/7, 2011 at 1:55 Comment(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;Tacye
K
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();
Keyek answered 27/7, 2011 at 0:39 Comment(4)
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(); ?Deviled
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.Keyek
getMonth() will return 0Decipher
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.Keyek

© 2022 - 2024 — McMap. All rights reserved.