人类可读格式的时间戳

新手上路,请多包涵

好吧,我在使用 javascript 从 unix 时间戳转换为人类表示时遇到了一个奇怪的问题

这是时间戳

1301090400

这是我的 javascript

var date = new Date(timestamp * 1000);
var year    = date.getFullYear();
var month   = date.getMonth();
var day     = date.getDay();
var hour    = date.getHours();
var minute  = date.getMinutes();
var seconds = date.getSeconds();

我预计结果是 2011 2, 25 22 00 00。但它是 2011, 2, 6, 0, 0, 0

我想念什么?

原文由 georgevich 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 936
2 个回答

getDay() 返回星期几。要获取日期,请使用 date.getDate()getMonth() 检索月份,但月份是从零开始的,因此使用 getMonth() + 1 应该会给您正确的月份。这里的时间值似乎没问题,尽管这里的时间是 23 (GMT+1)。如果您想要通用值,请将 UTC 添加到方法中(例如 date.getUTCFullYear()date.getUTCHours()

 const timestamp = 1301090400;
 const date = new Date(timestamp * 1000);
 const datevalues = [
 date.getFullYear(),
 date.getMonth()+1,
 date.getDate(),
 date.getHours(),
 date.getMinutes(),
 date.getSeconds(),
 ];
 alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]

这是一个检索给定 Date 值的小帮手想法:

 const dateHelper = dateHelperFactory();
 const formatMe = date => {
 const vals = `yyyy,mm,dd,hh,mmi,ss,mms`.split(`,`);
 const myDate = dateHelper(date).toArr(...vals);
 return `${myDate.slice(0, 3).join(`/`)} ${
 myDate.slice(3, 6).join(`:`)}.${
 myDate.slice(-1)[0]}`;
 };

 // to a formatted date with zero padded values
 console.log(formatMe(new Date(1301090400 * 1000)));

 // the raw values
 console.log(dateHelper(new Date(1301090400 * 1000)).values);

 function dateHelperFactory() {
 const padZero = (val, len = 2) => `${val}`.padStart(len, `0`);
 const setValues = date => {
 let vals = {
 yyyy: date.getFullYear(),
 m: date.getMonth()+1,
 d: date.getDate(),
 h: date.getHours(),
 mi: date.getMinutes(),
 s: date.getSeconds(),
 ms: date.getMilliseconds(), };
 Object.keys(vals).filter(k => k !== `yyyy`).forEach(k =>
 vals[k[0]+k] = padZero(vals[k], k === `ms` && 3 || 2) );
 return vals;
 };

 return date => ( {
 values: setValues(date),
 toArr(...items) { return items.map(i => this.values[i]); },
 } );
 }
 .as-console-wrapper {
 max-height: 100% !important;
 }

或者看看这个小的 stackblitz 项目(效率更高一点)。

原文由 KooiInc 发布,翻译遵循 CC BY-SA 4.0 许可协议

var newDate = new Date();
newDate.setTime(unixtime*1000);
dateString = newDate.toUTCString();

其中 unixtime 是您的 sql db 返回的时间。如果有帮助,这是一个 小提琴

例如,在当前时间使用它:

 document.write( new Date().toUTCString() );

原文由 Shouvik 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏