How do you convert a JavaScript date to UTC?

后端 未结 29 2094
无人共我
无人共我 2020-11-22 00:50

Suppose a user of your website enters a date range.

2009-1-1 to 2009-1-3

You need to send this date to a server for some processing, but th

29条回答
  •  一向
    一向 (楼主)
    2020-11-22 00:54

    yarn add moment

    import moment from 'moment';
    
    //local Js date to UTC using moment
    const utcDate = moment.utc(moment(new date()).format('YYYY-MM-DDTHH:mm:ss')).valueOf();
    console.log('UTC Date', utcDate);
    
    
    // UTC to local date without moment
    const localDate = convertUTCDateToLocalDate(new Date(utcDate))
    console.log('UTC Date', moment(localDate).format('MMM D, YYYY HH:mm'));
    
    
    function convertUTCDateToLocalDate(date) {
    
       let newDate = new Date(date.getTime() + date.getTimezoneOffset()*60*1000);
    
       const offset = date.getTimezoneOffset() / 60;
       const hours = date.getHours();
    
       newDate.setHours(hours - offset);
    
       return newDate;
    
    }

提交回复
热议问题