[英]Converting a mysql UTC_TIMESTAMP to CST and MST using Javascript
I've done endless searching but cannot find a solution that works for me. 我已经进行了无尽的搜索,但是找不到适合我的解决方案。 I am storing records in a mysql database that logs the UTC time it was created (UTC_TIMESTAMP()).
我将记录存储在mysql数据库中,该数据库记录创建它的UTC时间(UTC_TIMESTAMP())。 I need to present the data to the user (using JavaScript) in their local time.
我需要在本地时间向用户展示数据(使用JavaScript)。 I've tried the following and it is not working:
我尝试了以下方法,但无法正常工作:
JavaScript: JavaScript的:
function localizeDateStr(dateToConvert,divId){
newDate = new Date(dateToConvert);
document.getElementById(divId).innerHTML = newDate.toString();
}
HTML: HTML:
<div id="<?php echo $divId ?>" class="td-short"></div>
<script type="text/javascript">window.onload = localizeDateStr('<?php echo $entryTime;?>','<?php echo $divId;?>');</script>
The UTC date that is stored in the db is the same date that is being displayed.I am not seeing a converted date. 数据库中存储的UTC日期与显示的日期相同。我没有看到转换后的日期。 Any help would be appreciated.
任何帮助,将不胜感激。 Please advise.
请指教。
Parsing a string through the Date
constructor (or through Date.parse
) is very sensitive to the format of the input string. 通过
Date
构造函数(或通过Date.parse
)解析字符串对输入字符串的格式非常敏感。 With the value you gave in comments '2019-03-20 17:43:53'
, most implementations will interpret this in terms of local time . 借助您在注释
'2019-03-20 17:43:53'
给出的值, 大多数实现将以本地时间来解释这一点。 However, the specification does not require conformance of that, as it only describes a very particular format. 但是, 该规范不需要遵循该规范 ,因为它仅描述了一种非常特殊的格式。 Anything else is implementation dependent.
其他一切都取决于实现。
Assuming your strings are consistently in this format, and you want it interpreted as UTC, your options are: 假设您的字符串始终采用这种格式,并且希望将其解释为UTC,则可以选择:
Adjust the string to include a T
separator between date and time parts, and end with Z
to indicate UTC. 调整字符串以在日期和时间部分之间包括
T
分隔符,并以Z
结尾以指示UTC。
var newDate = new Date(dateToConvert.replace(' ','T') + 'Z');
Parse the string yourself: 自己解析字符串:
var parts = dateToConvert.split(/[-: ]/g).map((x) => parseInt(x)); parts[1]--; // Months are 0-11, so adjust var newDate = new Date(Date.UTC(...parts));
Use a library like Luxon : 使用类似Luxon的库:
var dt = luxon.DateTime.fromFormat(dateToConvert, 'yyyy-MM-dd HH:mm:ss', { zone: 'UTC' }); var newDate = dt.toJSDate();
var newDate = moment.utc(dateToConvert).toDate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.