将 MySql 日期时间戳转换为 JavaScript 的日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3075577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert MySql DateTime stamp into JavaScript's Date format
提问by dzm
Does anyone know how I can take a MySQL datetimedata type value, such as YYYY-MM-DD HH:MM:SSand either parse it or convert it to work in JavaScript's Date()function, for example:- Date('YYYY, MM, DD, HH, MM, SS);
有谁知道我如何获取 MySQLdatetime数据类型值,例如YYYY-MM-DD HH:MM:SS解析它或将其转换为在 JavaScript 的Date()函数中工作,例如:- Date('YYYY, MM, DD, HH, MM, SS);
Thank you!
谢谢!
回答by Andy E
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.
这里给出的一些答案要么过于复杂,要么就是行不通(至少,不是在所有浏览器中)。如果退后一步,您可以看到 MySQL 时间戳的每个时间分量与Date()构造函数所需的参数的顺序相同。
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 服务器正在输出 UTC 日期(这是默认值,如果字符串没有时区组件,则建议使用)。
回答by Marco Demaio
To add to the excellent Andy E answera function of common usage could be:
要添加到优秀的Andy E 答案中,常用的函数可能是:
Date.createFromMysql = function(mysql_string)
{
var t, result = null;
if( typeof mysql_string === 'string' )
{
t = mysql_string.split(/[- :]/);
//when t[3], t[4] and t[5] are missing they defaults to zero
result = new Date(t[0], t[1] - 1, t[2], t[3] || 0, t[4] || 0, t[5] || 0);
}
return result;
}
In this way given a MySQL date/time in the form "YYYY-MM-DD HH:MM:SS"or even the short form (only date) "YYYY-MM-DD"you can do:
通过这种方式给定 MySQL 日期/时间,"YYYY-MM-DD HH:MM:SS"甚至是简短的形式(仅日期),"YYYY-MM-DD"您可以执行以下操作:
var d1 = Date.createFromMysql("2011-02-20");
var d2 = Date.createFromMysql("2011-02-20 17:16:00");
alert("d1 year = " + d1.getFullYear());
回答by Symen Timmermans
I think I may have found a simpler way, that nobody mentioned.
我想我可能找到了一种更简单的方法,没有人提到过。
A MySQL DATETIME column can be converted to a unix timestamp through:
MySQL DATETIME 列可以通过以下方式转换为 unix 时间戳:
SELECT unix_timestamp(my_datetime_column) as stamp ...
We can make a new JavaScript Date object by using the constructor that requires milliseconds since the epoch. The unix_timestamp function returns seconds since the epoch, so we need to multiply by 1000:
我们可以通过使用自纪元以来需要毫秒的构造函数来创建一个新的 JavaScript Date 对象。unix_timestamp 函数返回自纪元以来的秒数,因此我们需要乘以 1000:
SELECT unix_timestamp(my_datetime_column) * 1000 as stamp ...
The resulting value can be used directly to instantiate a correct Javascript Date object:
结果值可以直接用于实例化一个正确的 Javascript Date 对象:
var myDate = new Date(<?=$row['stamp']?>);
Hope this helps.
希望这可以帮助。
回答by aleemb
One liner for modern browsers (IE10+):
现代浏览器(IE10+)的一个班轮:
var d = new Date(Date.parse("2010-06-09 13:12:01"));
alert(d); // Wed Jun 09 2010 13:12:01 GMT+0100 (GMT Daylight Time)
And just for fun, here's a one-liner that will work across older browsers (now fixed):
只是为了好玩,这里有一个可以跨旧浏览器工作的单行代码(现已修复):
new (Function.prototype.bind.apply(Date, [null].concat("2010-06-09 13:12:01".split(/[\s:-]/)).map(function(v,i){return i==2?--v:v}) ));
alert(d); // Wed Jun 09 2010 13:12:01 GMT+0100 (GMT Daylight Time)
回答by Jeff
Recent versions of JavaScript will read an ISO8601 formatted date, so all you have to do is change the space to a 'T', doing something like one of the following:
最新版本的 JavaScript 将读取 ISO8601 格式的日期,因此您只需将空格更改为“T”,执行以下操作之一:
#MySQL
select date_format(my_date_column,'%Y-%m-%dT%T') from my_table;
#PHP
$php_date_str = substr($mysql_date_str,0,10).'T'.substr($mysql_date_str,11,8);
//JavaScript
js_date_str = mysql_date_str.substr(0,10)+'T'+mysql_date_str.substr(11,8);
回答by Adrian Bartholomew
To add even further to Marco's solution. I prototyped directly to the String object.
进一步添加到 Marco 的解决方案中。我直接对 String 对象进行了原型设计。
String.prototype.mysqlToDate = String.prototype.mysqlToDate || function() {
var t = this.split(/[- :]/);
return new Date(t[0], t[1]-1, t[2], t[3]||0, t[4]||0, t[5]||0);
};
This way you can go directly to:
这样你就可以直接去:
var mySqlTimestamp = "2011-02-20 17:16:00";
var pickupDate = mySqlTimestamp.mysqlToDate();
回答by Caique Matos
There is a simpler way, sql timestamp string:
还有一个更简单的方法,sql时间戳字符串:
2018-07-19 00:00:00
2018-07-19 00:00:00
The closest format to timestamp for Date() to receive is the following, so replace blank space for "T":
Date() 接收的最接近时间戳的格式如下,因此将空格替换为“T”:
var dateString = media.intervention.replace(/\s/g, "T");
"2011-10-10T14:48:00"
“2011-10-10T14:48:00”
Then, create the date object:
然后,创建日期对象:
var date = new Date(dateString);
result would be the date object:
结果将是日期对象:
Thu Jul 19 2018 00:00:00 GMT-0300 (Horário Padr?o de Brasília)
2018 年 7 月 19 日星期四 00:00:00 GMT-0300 (Horário Padr?o de Brasília)
回答by jaym
From Andy's Answer, For AngularJS - Filter
来自安迪的回答,对于 AngularJS - 过滤器
angular
.module('utils', [])
.filter('mysqlToJS', function () {
return function (mysqlStr) {
var t, result = null;
if (typeof mysqlStr === 'string') {
t = mysqlStr.split(/[- :]/);
//when t[3], t[4] and t[5] are missing they defaults to zero
result = new Date(t[0], t[1] - 1, t[2], t[3] || 0, t[4] || 0, t[5] || 0);
}
return result;
};
});
回答by sbrbot
First you can give JavaScript's Date object (class) the new method 'fromYMD()' for converting MySQL's YMD date format into JavaScript format by splitting YMD format into components and using these date components:
首先,您可以通过将 YMD 格式拆分为组件并使用这些日期组件,为 JavaScript 的 Date 对象(类)提供新方法“fromYMD()”,用于将 MySQL 的 YMD 日期格式转换为 JavaScript 格式:
Date.prototype.fromYMD=function(ymd)
{
var t=ymd.split(/[- :]/); //split into components
return new Date(t[0],t[1]-1,t[2],t[3]||0,t[4]||0,t[5]||0);
};
Now you can define your own object (funcion in JavaScript world):
现在您可以定义自己的对象(JavaScript 世界中的函数):
function DateFromYMD(ymd)
{
return (new Date()).fromYMD(ymd);
}
and now you can simply create date from MySQL date format;
现在您可以简单地从 MySQL 日期格式创建日期;
var d=new DateFromYMD('2016-07-24');
回答by bhowden
var a=dateString.split(" ");
var b=a[0].split("-");
var c=a[1].split(":");
var date = new Date(b[0],(b[1]-1),b[2],b[0],c[1],c[2]);

