Javascript to convert UTC to local time

后端 未结 8 952
暖寄归人
暖寄归人 2020-11-27 06:23

Okay, say JSON parse string UTC date as below:

2012-11-29 17:00:34 UTC

Now if I want to convert this UTC date to my local time, how can I d

相关标签:
8条回答
  • 2020-11-27 06:54

    To format your date try the following function:

    var d = new Date();
    var fromatted = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");
    

    But the downside of this is, that it's a non-standard function, which is not working in Chrome, but working in FF (afaik).

    Chris

    0 讨论(0)
  • 2020-11-27 06:54

    You could take a look at date-and-time api for easily date manipulation.

    let now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss', true);
    console.log(now);
    <script src="https://cdn.jsdelivr.net/npm/date-and-time/date-and-time.min.js"></script>

    0 讨论(0)
  • 2020-11-27 06:55
    var offset = new Date().getTimezoneOffset();
    

    offset will be the interval in minutes from Local time to UTC. To get Local time from a UTC date, you would then subtract the minutes from your date.

    utc_date.setMinutes(utc_date.getMinutes() - offset);
    
    0 讨论(0)
  • 2020-11-27 06:56

    Try:

    var date = new Date('2012-11-29 17:00:34 UTC');
    date.toString();
    
    0 讨论(0)
  • 2020-11-27 07:01
    /*
     * convert server time to local time
     *  simbu
    */
    function convertTime(serverdate) {
        var date = new Date(serverdate);
        // convert to utc time
        var toutc = date.toUTCString();
        //convert to local time
        var locdat = new Date(toutc + " UTC");
        return locdat;
    }
    
    0 讨论(0)
  • 2020-11-27 07:03

    Here is another option that outputs mm/dd/yy:

    const date = new Date('2012-11-29 17:00:34 UTC');
    date.toLocaleString();
    //output 11/29/2012
    
    0 讨论(0)
提交回复
热议问题