将MySQL日期时间转换为Javascript Date.UTC格式(对于Highcharts非常有用)

Been breaking my head for the past couple of hours to solve a tiny issue in my Highcharts chart with a timeline, so here is my solution. Use it to your benefit.

The issue is that you can't just use the timestamp from an MySQL database (format: Y-m-d H:i:s) in the Highchart script as the Javascript Date.UTC counts the months differently... minus 1 so from January = 0 to December = 11 *arrggg*

I've tried several proposed solutions for a conversion directly in the MySQL query but noticed that this resulted in incorrect results, so I abandoned that approach and went for a little PHP based function instead:

function format_as_jsDateUTC( $timestamp )
{
    $dt = DateTime::createFromFormat( 'Y-m-d H:i:s', $timestamp ); 
    $ret = $dt->format('Y, '); 
    $ret .= $dt->format('n')-1 == 0 ? 0 : $dt->format('n')-1;  
    $ret .= $dt->format(', j, G, i, s');
    /** 
     * [Y] full numeric representation of a year, 4 digits
     * [n] numeric representation of a month, without leading zero, minus 1 for usage in Javascript (from January = 0 to December = 11)
     * [j] day of the month without leading zeros
     * [G] 24-hour format of an hour without leading zeros
     * [i] minutes with leading zeros
     * [s] seconds with leading zeros
     */  
    return $ret;
}

echo format_as_jsDateUTC( '2017-01-05 09:08:07' );
// results in: 2017, 0, 5, 9, 08, 07

If anyone has any improvements or does know a correct way for achieving this in directly in my SELECT query then I'm always interested to hear as I can only learn from the feedback :)

Last but not least - in the jQuery code for my zoomable Highchart spline chart I used it as:

pointStart: Date.UTC(<?php echo format_as_jsDateUTC( $stats['date'] ); ?>)

See also the full Highcharts code (without the PHP as it's on JSFiddle) at: http://jsfiddle.net/golabs/hfj6mug1/

dongyuyi5680
dongyuyi5680 如果您遇到时区问题,请查看api.highcharts.com/highcharts/global.useUTC。任何格式化需要删除秒应该完全涵盖各种格式化程序功能和各种日期格式设置。对于更具体的指针,设置一个小提琴,显示你需要帮助格式化的东西(尽管最好开始一个新的帖子)
3 年多之前 回复
dongsuoying9059
dongsuoying9059 测试它,并顺利运行:)只需将其更改为(strtotime($timestamp)+3600)*1000来纠正时区。在Highchart中,该行变为:pointStart:<?phpechoformat_as_jsDateUTC($stats['date']);?>而不是pointStart:Date.UTC(<?phpechoformat_as_jsDateUTC($stats['date']);?>)。当我找不到在Highchart标签上格式化秒数的方法时,我可能会坚持我的功能,因为我可以强制秒为0,因此它们不会出现在标签中。谢谢!
3 年多之前 回复
dongmen1925
dongmen1925 将$timestamp转换为纪元时间,乘以1,000(php转换为秒,javascript使用毫秒)。所以,strtotime($timestamp)*1000将为Highcharts提供一个可用的javascript时间戳。
3 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问