繁体   English   中英

在刷新中格式化日期和时间

[英]Format date and time in refresh

我想使用以下脚本每秒刷新时间。 工作正常,但我希望它输出这样的格式:

10 月 6 日 - 13:38:04。

你是怎样做的?

 var timestamp = '<?=time();?>'; function updateTime(){ const firstOption = {month: 'long', day: 'numeric'}; const secondOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric' }; $('#time').html(new Date(timestamp).toLocaleDateString("en-NL", firstOption) + " - " + new Date(timestamp).toLocaleTimeString("en-NL", secondOptions)); timestamp++; } $(function(){ setInterval(updateTime, 1000); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p id="time"></p>

尝试这个:

 const firstOption = {month: 'long', day: 'numeric'};
 const secondOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric' };
$('#time').html(new Date(timestamp).toLocaleDateString("en-NL", firstOption) + " - " + new Date(timestamp).toLocaleTimeString("en-NL", secondOptions));

在此处阅读更多相关信息。

用于格式化日期的简单功能。

function dateToString(/* add timestamp parameter if you want */) {
  
  var d = new Date(/* timestamp parameter here */);

  var months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'October',
    'November',
    'December',
  ]
  
  var month = months[d.getMonth() - 1];
  var date = (d.getDate() < 10) ? "0" + d.getDate() : d.getDate();
  var hours = d.getHours(),
      minutes = d.getMinutes(),
      seconds = d.getSeconds();
  
  var time = (hours < 10 ? "0" + hours : hours) + ':' + (minutes < 10 ? "0" + 
minutes : minutes) + ':' + (seconds < 10 ? "0" + seconds : seconds);
  
  return month + ' ' + date + ' - ' + time;
}

dateToString(/* pass timestamp argument here */);

Afaik PHP 的time函数返回一个 unix 时间戳,您正在寻找 ES5 解决方案。 这可能对你有帮助。

 const datetime = 1601984483; var padStart = function(str, length) { while (str.toString().length < length) str = "0" + str; return str; } var format = function (timestamp) { var date = new Date(); var d = { M: date.toLocaleString('default', { month: 'long' }), d: padStart(date.getDate(), 2), h: padStart(date.getHours(), 2), m: padStart(date.getMinutes(), 2), s: padStart(date.getSeconds(), 2) }; return [[dM, dd].join(' '), [dh, dm, ds].join(':')].join(' '); } console.log(format(datetime));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM