javascriptgettime

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


Solution

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