Convert UTC date time to local date time

前端 未结 30 1180
悲哀的现实
悲哀的现实 2020-11-22 01: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 us

相关标签:
30条回答
  • 2020-11-22 01:42

    I've created one function which converts all the timezones into local time.

    I did not used getTimezoneOffset(), because it does not returns proper offset value

    Requirements:

    1. npm i moment-timezone
    
    function utcToLocal(utcdateTime, tz) {
        var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
        var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
        var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
        var localDateTime
        var hours = zoneValue.split(":")[0]
        var minutes = zoneValue.split(":")[1]
        if (operator === "-") {
            localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
        } else if (operator) {
            localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
        } else {
            localDateTime = "Invalid Timezone Operator"
        }
        return localDateTime
    }
    
    utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")
    
    //Returns "2019-11-14 12:45:37"
    
    0 讨论(0)
  • 2020-11-22 01:43

    In my point of view servers should always in the general case return a datetime in the standardized ISO 8601-format.

    More info here:

    • http://www.w3.org/TR/NOTE-datetime
    • https://en.wikipedia.org/wiki/ISO_8601

    IN this case the server would return '2011-06-29T16:52:48.000Z' which would feed directly into the JS Date object.

    var utcDate = '2011-06-29T16:52:48.000Z';  // ISO-8601 formatted date returned from server
    var localDate = new Date(utcDate);
    

    The localDate will be in the right local time which in my case would be two hours later (DK time).

    You really don't have to do all this parsing which just complicates stuff, as long as you are consistent with what format to expect from the server.

    0 讨论(0)
  • 2020-11-22 01:43

    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,""));
    
    0 讨论(0)
  • 2020-11-22 01:43

    For me, this works well

    if (typeof date === "number") {
      time = new Date(date).toLocaleString();
      } else if (typeof date === "string"){
      time = new Date(`${date} UTC`).toLocaleString();
    }
    
    0 讨论(0)
  • 2020-11-22 01:46

    Add the time zone at the end, in this case 'UTC':

    theDate = new Date( Date.parse('6/29/2011 4:52:48 PM UTC'));
    

    after that, use toLocale()* function families to display the date in the correct locale

    theDate.toLocaleString();  // "6/29/2011, 9:52:48 AM"
    theDate.toLocaleTimeString();  // "9:52:48 AM"
    theDate.toLocaleDateString();  // "6/29/2011"
    
    0 讨论(0)
  • 2020-11-22 01:47

    Use this for UTC and Local time convert and vice versa.

    //Covert datetime by GMT offset 
    //If toUTC is true then return UTC time other wise return local time
    function convertLocalDateToUTCDate(date, toUTC) {
        date = new Date(date);
        //Local time converted to UTC
        console.log("Time: " + date);
        var localOffset = date.getTimezoneOffset() * 60000;
        var localTime = date.getTime();
        if (toUTC) {
            date = localTime + localOffset;
        } else {
            date = localTime - localOffset;
        }
        date = new Date(date);
        console.log("Converted time: " + date);
        return date;
    }
    
    0 讨论(0)
提交回复
热议问题