Convert UTC date time to local date time

2018-12-31 06:09发布

From the server I get a datetime variable in this format: 6/29/2011 4:52:48 PM and it is in UTC time. I want to convert it to the current user’s browser time using JavaScript.

How this can be done using JavaScript or jQuery?

23条回答
流年柔荑漫光年
2楼-- · 2018-12-31 07:02

I wrote a nice little script that takes a UTC epoch and converts it the client system timezone and returns it in d/m/Y H:i:s (like the PHP date function) format:

getTimezoneDate = function ( e ) {

    function p(s) { return (s < 10) ? '0' + s : s; }        

    var t = new Date(0);
    t.setUTCSeconds(e);

    var d = p(t.getDate()), 
        m = p(t.getMonth()+1), 
        Y = p(t.getFullYear()),
        H = p(t.getHours()), 
        i = p(t.getMinutes()), 
        s = p(t.getSeconds());

    d =  [d, m, Y].join('/') + ' ' + [H, i, s].join(':');

    return d;

};
查看更多
余生请多指教
3楼-- · 2018-12-31 07:03

For me above solutions didn't work.

With IE the UTC date-time conversion to local is little tricky. For me, the date-time from web API is '2018-02-15T05:37:26.007' and I wanted to convert as per local timezone so I used below code in JavaScript.

var createdDateTime = new Date('2018-02-15T05:37:26.007' + 'Z');
查看更多
谁念西风独自凉
4楼-- · 2018-12-31 07:03

To me the simplest seemed using

datetime.setUTCHours(datetime.getHours());
datetime.setUTCMinutes(datetime.getMinutes());

(i thought the first line could be enough but there are timezones which are off in fractions of hours)

查看更多
妖精总统
5楼-- · 2018-12-31 07:04

Put this function in your head:

<script type="text/javascript">
function localize(t)
{
  var d=new Date(t+" UTC");
  document.write(d.toString());
}
</script>

Then generate the following for each date in the body of your page:

<script type="text/javascript">localize("6/29/2011 4:52:48 PM");</script>

To remove the GMT and time zone, change the following line:

document.write(d.toString().replace(/GMT.*/g,""));
查看更多
孤独寂梦人
6楼-- · 2018-12-31 07:05

A JSON date string (serialized in C#) looks like "2015-10-13T18:58:17".

In angular, (following Hulvej) make a localdate filter:

myFilters.filter('localdate', function () {
    return function(input) {
        var date = new Date(input + '.000Z');
        return date;
    };
})

Then, display local time like:

{{order.createDate | localdate | date : 'MMM d, y h:mm a' }}
查看更多
登录 后发表回答