JavaScript datetime parsing(JavaScript 日期时间解析)
问题描述
可能重复:
如何将字符串转换为日期时间JavaScript 中的格式规范?
我有一个 json 响应,其中包含一个类似的哈希图;
I have a json response which contains a hashmap like;
{"map":{"2012-10-10 03:47:00.0":23.400000000000002,"2012-10-10 03:52:00.0":23.3,"2012-10-10 03:57:00.0":23.3,"2012-10-10 04:02:00.0":23.3,"2012-10-10 04:07:00.0":23.200000000000003,"2012-10-10 04:13:00.0":23.1,"2012-10-10 04:18:00.0":23.1,"2012-10-10 04:23:00.0":23.0,"2012-10-10 04:28:00.0":23.0,"2012-10-10 04:33:00.0":23.0,"2012-10-10 04:38:00.0":22.900000000000002,"2012-10-10 04:43:00.0":22.8,"2012-10-10 04:48:00.0":22.8,"2012-10-10 04:53:00.0":22.700000000000003,"2012-10-10 04:58:00.0":22.6,"2012-10-10 05:03:00.0":22.6,"2012-10-10 05:08:00.0":22.5,"2012-10-10 05:13:00.0":22.5,"2012-10-10 05:18:00.0":22.5,"2012-10-10 05:23:00.0":22.400000000000002}}
我想格式化 json 的日期时间部分,例如;
I want to format datetime part of json like;
dd/mm/yyyy HH:mm:ss
dd/mm/yyyy HH:mm:ss
假设我把所有的pair元素都这样放置;
Lets assume I put all pair elements like this;
var myArr = [["2012-10-10 03:47:00.0", 23.400000000000002], ["2012-10-10 03:52:00.0", 23.3], ....];
然后,我尝试解析日期时间部分,如下所示,我在控制台上得到 Date {Invalid Date};
Then, I try to parse datetime part like below and I got Date {Invalid Date} on console;
new Date(myArr[0][0]);
如何格式化这种类型的日期时间.
How can I format this type of datetime.
推荐答案
试试以下:
new Date(Date.parse(myArr[0][0]));
示例
使用日期.parse 方法将字符串解析为自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数.取那个毫秒数并再次调用 Date 方法来转动那个时间到一个日期对象中.
Use the Date.parse method to parse the string into the number of milliseconds since January 1, 1970, 00:00:00 UTC. Take that number of milliseconds and call the Date method once again to turn that time into a date object.
编辑:
好吧,对于这种情况,这可能有点难看,但似乎 Firefox 的 -s 和 00.0 存在问题.
Well this may be a little ugly for this case, but it seems Firefox is having an issue with the -s and the 00.0.
var myArr = [["2012-10-10 03:47:00.0", 23.400000000000002], ["2012-10-10 03:52:00.0", 23.3]];
var date = convertDateTime(myArr[0][0]);
console.log(date);
function convertDateTime(dateTime){
dateTime = myArr[0][0].split(" ");
var date = dateTime[0].split("-");
var yyyy = date[0];
var mm = date[1]-1;
var dd = date[2];
var time = dateTime[1].split(":");
var h = time[0];
var m = time[1];
var s = parseInt(time[2]); //get rid of that 00.0;
return new Date(yyyy,mm,dd,h,m,s);
}
示例
这篇关于JavaScript 日期时间解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript 日期时间解析
基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
