Convert UTC Epoch to local date

后端 未结 16 1512
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 10:10

I have been fighting with this for a bit now. I’m trying to convert epoch to a date object. The epoch is sent to me in UTC. Whenever you pass new Date() an epoc

相关标签:
16条回答
  • 2020-11-22 10:49

    To convert the current epoch time in [ms] to a 24-hour time. You might need to specify the option to disable 12-hour format.

    $ node.exe -e "var date = new Date(Date.now()); console.log(date.toLocaleString('en-GB', { hour12:false } ));"
    
    2/7/2018, 19:35:24
    

    or as JS:

    var date = new Date(Date.now()); 
    console.log(date.toLocaleString('en-GB', { hour12:false } ));
    // 2/7/2018, 19:35:24
    
    console.log(date.toLocaleString('en-GB', { hour:'numeric', minute:'numeric', second:'numeric', hour12:false } ));
    // 19:35:24
    

    Note: The use of en-GB here, is just a (random) choice of a place using the 24 hour format, it is not your timezone!

    0 讨论(0)
  • The simplest solution I've found to this, is:

    var timestamp = Date.now(), // returns milliseconds since epoch time
        normalisedTime = new Date(timestamp);
    

    Notice this doesn't have the * 1000 at the end of new Date(timestamp) statement as this (for me anyway!) always seems to give out the wrong date, ie instead of giving the year 2019 it gives the year as 51015, so just bear that in mind.

    0 讨论(0)
  • 2020-11-22 10:56
     function ToLocalDate (inDate) {
        var date = new Date();
        date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset());
        return date;
    }
    
    0 讨论(0)
  • 2020-11-22 10:56

    If you prefer to resolve timestamps and dates conversions from and to UTC and local time without libraries like moment.js, take a look at the option below.

    For applications that use UTC timestamps, you may need to show the date in the browser considering the local timezone and daylight savings when applicable. Editing a date that is in a different daylight savings time even though in the same timezone can be tricky.

    The Number and Date extensions below allow you to show and get dates in the timezone of the timestamps. For example, lets say you are in Vancouver, if you are editing a date in July or in December, it can mean you are editing a date in PST or PDT.

    I recommend you to check the Code Snippet down below to test this solution.

    Conversions from milliseconds

    Number.prototype.toLocalDate = function () {
        var value = new Date(this);
    
        value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));
    
        return value;
    };
    
    Number.prototype.toUTCDate = function () {
        var value = new Date(this);
    
        value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
    
        return value;
    };
    

    Conversions from dates

    Date.prototype.getUTCTime = function () {
        return this.getTime() - (this.getTimezoneOffset() * 60000);
    };
    

    Usage

    // Adds the timezone and daylight savings if applicable
    (1499670000000).toLocalDate();
    
    // Eliminates the timezone and daylight savings if applicable
    new Date(2017, 6, 10).getUTCTime();
    

    See it for yourself

    // Extending Number
    
    Number.prototype.toLocalDate = function () {
        var value = new Date(this);
    
        value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));
    
        return value;
    };
    
    Number.prototype.toUTCDate = function () {
        var value = new Date(this);
    
        value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
    
        return value;
    };
    
    // Extending Date
    
    Date.prototype.getUTCTime = function () {
        return this.getTime() - (this.getTimezoneOffset() * 60000);
    };
    
    // Getting the demo to work
    document.getElementById('m-to-local-button').addEventListener('click', function () {
      var displayElement = document.getElementById('m-to-local-display'),
          value = document.getElementById('m-to-local').value,
          milliseconds = parseInt(value);
      
      if (typeof milliseconds === 'number')
        displayElement.innerText = (milliseconds).toLocalDate().toISOString();
      else
        displayElement.innerText = 'Set a value';
    }, false);
    
    document.getElementById('m-to-utc-button').addEventListener('click', function () {
      var displayElement = document.getElementById('m-to-utc-display'),
          value = document.getElementById('m-to-utc').value,
          milliseconds = parseInt(value);
      
      if (typeof milliseconds === 'number')
        displayElement.innerText = (milliseconds).toUTCDate().toISOString();
      else
        displayElement.innerText = 'Set a value';
    }, false);
    
    document.getElementById('date-to-utc-button').addEventListener('click', function () {
      var displayElement = document.getElementById('date-to-utc-display'),
          yearValue = document.getElementById('date-to-utc-year').value || '1970',
          monthValue = document.getElementById('date-to-utc-month').value || '0',
          dayValue = document.getElementById('date-to-utc-day').value || '1',
          hourValue = document.getElementById('date-to-utc-hour').value || '0',
          minuteValue = document.getElementById('date-to-utc-minute').value || '0',
          secondValue = document.getElementById('date-to-utc-second').value || '0',
          year = parseInt(yearValue),
          month = parseInt(monthValue),
          day = parseInt(dayValue),
          hour = parseInt(hourValue),
          minute = parseInt(minuteValue),
          second = parseInt(secondValue);
      
      displayElement.innerText = new Date(year, month, day, hour, minute, second).getUTCTime();
    }, false);
    <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.11/semantic.css" rel="stylesheet"/>
    
    <div class="ui container">
      <p></p>
      
      <h3>Milliseconds to local date</h3>
      <input id="m-to-local" placeholder="Timestamp" value="0" /> <button id="m-to-local-button">Convert</button>
      <em id="m-to-local-display">Set a value</em>
    
      <h3>Milliseconds to UTC date</h3>
      <input id="m-to-utc" placeholder="Timestamp" value="0" /> <button id="m-to-utc-button">Convert</button>
      <em id="m-to-utc-display">Set a value</em>
      
      <h3>Date to milliseconds in UTC</h3>
      <input id="date-to-utc-year" placeholder="Year" style="width: 4em;" />
      <input id="date-to-utc-month" placeholder="Month" style="width: 4em;" />
      <input id="date-to-utc-day" placeholder="Day" style="width: 4em;" />
      <input id="date-to-utc-hour" placeholder="Hour" style="width: 4em;" />
      <input id="date-to-utc-minute" placeholder="Minute" style="width: 4em;" />
      <input id="date-to-utc-second" placeholder="Second" style="width: 4em;" />
      <button id="date-to-utc-button">Convert</button>
      <em id="date-to-utc-display">Set the values</em>
      
    </div>

    0 讨论(0)
  • 2020-11-22 10:57

    @Amjad, good idea, but a better implementation would be:

    Date.prototype.setUTCTime = function(UTCTimestamp) {
        var UTCDate = new Date(UTCTimestamp);
        this.setUTCFullYear(UTCDate.getFullYear(), UTCDate.getMonth(), UTCDate.getDate());
        this.setUTCHours(UTCDate.getHours(), UTCDate.getMinutes(), UTCDate.getSeconds(), UTCDate.getMilliseconds());
        return this.getTime();
    }
    
    0 讨论(0)
  • 2020-11-22 11:01

    I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890. To convert that to a proper date in the local time zone:

    var utcSeconds = 1234567890;
    var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
    d.setUTCSeconds(utcSeconds);
    

    d is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)

    0 讨论(0)
提交回复
热议问题