将MySql DateTime戳记转换为JavaScript的Date格式 [英] Convert MySql DateTime stamp into JavaScript's Date format

查看:479
本文介绍了将MySql DateTime戳记转换为JavaScript的Date格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何使用MySQL datetime 数据类型值,例如 YYYY-MM-DD HH:MM:SS ,并解析它或转换为JavaScript的 Date()函数,例如: - Date('YYYY,MM,DD,HH,MM ,SS);



谢谢!

解决方案

这里提供的答案要么过于复杂,要么只是不行(至少不是在所有浏览器中)。如果您退后一步,您可以看到,MySQL时间戳记的每个时间分量的顺序与 Date()构造函数所要求的参数相同。



所有需要的是一个非常简单的分割字符串:

  //分割时间戳到[Y,M,D,h,m,s] 
var t =2010-06-09 13:12:01.split(/ [ - :] /);

//将每个元素应用于Date函数
var d = new Date(Date.UTC(t [0],t [1] -1,t [2],t [ 3],t [4],t [5]));

console.log(d);
// - > Wed Jun 09 2010 14:12:01 GMT + 0100(BST)

公平警告:这假设您的MySQL服务器正在输出UTC日期(这是默认值,如果没有字符串的时区组件,则建议使用)。


Does anyone know how I can take a MySQL datetime data type value, such as YYYY-MM-DD HH:MM:SS and either parse it or convert it to work in JavaScript's Date() function, for example:- Date('YYYY, MM, DD, HH, MM, SS);

Thank you!

解决方案

Some of the answers given here are either overcomplicated or just will not work (at least, not in all browsers). If you take a step back, you can see that the MySQL timestamp has each component of time in the same order as the arguments required by the Date() constructor.

All that's needed is a very simple split on the string:

// Split timestamp into [ Y, M, D, h, m, s ]
var t = "2010-06-09 13:12:01".split(/[- :]/);

// Apply each element to the Date function
var d = new Date(Date.UTC(t[0], t[1]-1, t[2], t[3], t[4], t[5]));

console.log(d);
// -> Wed Jun 09 2010 14:12:01 GMT+0100 (BST)

Fair warning: this assumes that your MySQL server is outputting UTC dates (which is the default, and recommended if there is no timezone component of the string).

这篇关于将MySql DateTime戳记转换为JavaScript的Date格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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