JavaScript日期时间解析 [英] JavaScript datetime parsing

查看:130
本文介绍了JavaScript日期时间解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何使用JavaScript中的格式规范将字符串转换为datetime?

我有一个json响应,其中包含一个hashmap;

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的datetime部分;

I want to format datetime part of json like;


dd / mm / yyyy HH:mm:ss

dd/mm/yyyy HH:mm:ss

假设我把所有的元素都像这样;

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], ....];

然后,我尝试解析datetime部分,如下所示,我有 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]));

示例

EXAMPLE

使用 Date 解析方法将字符串解析为自1970年1月1日00:00:00 UTC以来的毫秒数。采取毫秒数,并再次呼叫日期方法来转换时间成为日期对象。

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似乎与 - 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);
}

示例

EXAMPLE

这篇关于JavaScript日期时间解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆