将unix时间戳转换为javascript日期时间的最佳方法
Best way to convert a unix timestamp to javascript date-time
我一直遵循将Unix时间戳转换为JavaScript线程中的时间的答案,但看起来像个位数时间(0-9)被解析为它是。被接受的答案
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
我们得到2:3:9而不是02:03:09。如何摆脱这种行为?还有谁能详细说明一下如何随着时间的推移得到上午/下午?
var formattedTime = ('0' + hours).substr(-2) + ':'
+ ('0' + minutes).substr(-2) + ':'
+ ('0' + seconds).substr(-2);
我想我会把上午的部分留给你。按ctrl + shift + j,在控制台中运行代码
// /*Year m-1 d h m s ms*/
unix_timestamp = Math.floor(new Date(2016,0, 1,5,5,0,0)/1000)
这可能更容易理解。我把它放得更近了
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var amPm = date.getHours() >= 12?'AM':'PM'
// % is modulo which is the remainder after division || will change 0 to 12
// because 0 is falsey everything else will be left as it is
var hours = ("0" + ((date.getHours() % 12)||12)).substr(-2)
// Minutes part from the timestamp
var minutes = ("0" + date.getMinutes()).substr(-2)
// Seconds part from the timestamp
var seconds = ("0" + date.getSeconds()).substr(-2)
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes+ ':' + seconds + ' '+ amPm
我认为你必须去掉substr
-部分,因为值应该已经是正确的。
注意:您需要检查值是否已经大于9,因为当它大于9时,您不需要添加任何内容。
var d = new Date() //Is in milliseconds
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
console.log(hours + ":" + ((minutes < 10) ? "0" + minutes : minutes) + ":" + ((seconds < 10) ? "0" + seconds : seconds))
我想补充的是,这些问题可以很容易地解决,使用一个好的库,如moment.js
相关文章:
- Java脚本时间添加
- Json数据包含日期和时间格式
- 如何根据时间运行不同的脚本
- 用于查找基于时间的事件的最佳Javascript算法
- 删除上午、下午拖尾时间的最佳方式
- jquery 移动版的最佳绑定时间
- 查找开始时间和结束时间数组之间的间隔的最佳方法是什么
- 将时间戳发送到 JavaScript 的最佳格式
- 什么时候是调用webview.clearData的最佳时间
- JavaScript:时间戳的最佳格式
- 最佳实践:在Javascript中运行很长时间的轮询过程
- 确保内容在有时间限制的环境中随时可用的最佳方式
- 对于动态变化的时间,设置nvd3 x域范围的最佳方法是什么
- 创建基于时间的动态事件(如建筑施工时间等)的最佳方式是什么
- 将unix时间戳转换为javascript日期时间的最佳方法
- 获得准确时间戳的最佳方法
- 在react js中切换持续时间的最佳实践
- 在客户端和服务器之间传输日期时间的最佳方式(c#/javascript)
- chrome扩展-在使用内容脚本时减少加载时间的最佳方法
- 在Node.JS中输出用户所在时区时间戳的最佳方法