Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 565
jQuerybeast Avatar asked Jul 27 '11 00:07

jQuerybeast


People also ask

What is toLocaleTimeString () in JavaScript?

The toLocaleTimeString() method returns a string with a language-sensitive representation of the time portion of the date. In implementations with Intl. DateTimeFormat API support, this method simply calls Intl. DateTimeFormat .

What is locale date string?

The toLocaleDateString() method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with Intl. DateTimeFormat API support, this method simply calls Intl. DateTimeFormat .

How do you get toLocaleString time?

To get the current date and time in JavaScript, you can use the toLocaleString() method, which returns a string representing the given date according to language-specific conventions. To display only the time, you can use the toLocaleTimeString() method.


2 Answers

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());
like image 132
kennebec Avatar answered Oct 21 '22 04:10

kennebec


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();
like image 31
Tom Avatar answered Oct 21 '22 05:10

Tom