jQuerybeast
jQuerybeast

Reputation: 14490

Get local Date string and time string

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

Upvotes: 6

Views: 40946

Answers (2)

Tom
Tom

Reputation: 9127

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();

Upvotes: 9

kennebec
kennebec

Reputation: 104780

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());

Upvotes: 18

Related Questions