Javascript 获取本地日期字符串和时间字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6838197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:24:06  来源:igfitidea点击:

Get local Date string and time string

javascriptgettime

提问by jQuerybeast

I am trying to get the LocaleDateStringand the LocaleTimeStringwhich that would be toLocaleString()but LocaleString gives you GMT+0100 (GMT Daylight Time)which I wouldn't it to be shown.

我正在尝试获取LocaleDateStringLocaleTimeString,它们将是toLocaleString()但 LocaleString 为您提供GMT+0100(GMT 夏令时),我不会显示它。

Can I use something like:

我可以使用类似的东西:

timestamp = (new Date()).toLocaleDateString()+toLocaleTimeString();

Thanks alot

非常感谢

回答by kennebec

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.

此示例用前导 0 填充个位数并调整 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());

回答by Tom

If you build up the string using vanilla methods, it will do locale (and TZ) conversion automatically.

如果您使用 vanilla 方法构建字符串,它将自动进行区域设置(和 TZ)转换。

E.g.

例如

var dNow = new Date();
var s = ( dNow.getMonth() + 1 ) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();