dongshuming7131 2017-01-05 19:44
浏览 84

将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/

  • 写回答

0条回答

    报告相同问题?

    悬赏问题

    • ¥50 易语言把MYSQL数据库中的数据添加至组合框
    • ¥20 求数据集和代码#有偿答复
    • ¥15 关于下拉菜单选项关联的问题
    • ¥20 java-OJ-健康体检
    • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
    • ¥15 使用phpstudy在云服务器上搭建个人网站
    • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
    • ¥15 vue3+express部署到nginx
    • ¥20 搭建pt1000三线制高精度测温电路
    • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况