我想知道什么是这种格式的时间戳转换的最佳方式 -时间戳转换的JavaScript
2012-02-18 14:28:32
这种格式的日期显示格式 -
Saturday Feb 2012 14:28:32
非常感谢:)
我想知道什么是这种格式的时间戳转换的最佳方式 -时间戳转换的JavaScript
2012-02-18 14:28:32
这种格式的日期显示格式 -
Saturday Feb 2012 14:28:32
非常感谢:)
javascript日期函数是很糟糕...你必须转换为UTC http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_toutcstring
的选项,但如果是我,我会去了解一下Datejs:http://www.datejs.com/最好的JavaScript API日期对我来说
请看看在开始使用Datejs:http://www.datejs.com/2007/11/27/getting-started-with-datejs/
w3schools也很糟糕 - http://www.w3fools.com – ThiefMaster 2012-02-18 18:46:00
JavaScripts日期对象缺少格式化方法。我会考虑使用外部库,如this one。似乎它有你在找什么。
试试这个博客有足够的DateFormats:
您必须首先定义的英文单词(周日,周一,二月,三月,等)的数组:
var daysOfWeek = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
monthsOfYear = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
为了能够插入在分秒开始的额外0
,限定的填充功能为String
原型:
String.prototype.padLeft = function(padString,length){
var toReturn = String(this);
while(toReturn.length < length){
toReturn = padString + toReturn;
}
return toReturn;
}
格式这样的日期和时间:
var time = new Date(), formattedDate, formattedTime, wholeThing;
formattedDate = daysOfWeek[time.getDay()] + ", " + monthsOfYear[time.getMonth()] + " " + time.getDate() + ", " + time.getFullYear();
formattedTime = time.getHours() + ":" + time.getMinutes().padLeft("0",2) + time.getSeconds().padLeft("0",2);
您可以通过连接formattedDate
和formattedTime
,在得到整个事情:
wholeThing = formattedDate + " " + formattedTime;
考虑使用datejs
这是石头!
var mydate = Date.parse('2012-02-18 14:28:32');
var result = mydate.toString('dddd MMM yyyy h:mm:ss');
console.log(result);
感谢您的第2行! – user1202278 2012-02-18 18:58:36
???未捕获的RangeError:toString()基数参数必须介于2和36之间 处于Number。toString(
@PaoloBiavati这意味着你在一个数字上调用'toString',而不是Date:https://stackoverflow.com/questions/16527109/javascript-date-tostring-radix-argument -error(使用datejs)。 – Ehvince 2017-07-28 17:53:54
我建议使用外部js库来做到这一点。据我的理解,Moment.js是那里最好的日期 - 时间转换库。
在这种情况下,它在一行中完成这项工作。只需添加moment.js在你的项目,然后做
var timestamp = '2012-02-18 14:28:32';
var formattedTime = moment(timestamp).format('dddd MMM YYYY HH:mm:ss'); // Saturday Feb 2012 14:28:32
至于格式化到最终的字符串,我可以建议你[以下库(http://blog.stevenlevithan.com/archives/date-time -格式)。就问题的第一部分而言,您可以参考[以下问题](http://stackoverflow.com/questions/9229213/convert-iso-date-to-milliseconds-in-javascript/9229384) – Oybek 2012-02-18 18:41:19