Get offset from datetime string and apply to a new date object












0















I have a datetime string returned from my backend like this:



2018-12-30T20:00:00-05:00


I am trying to get the offset from this datetime string and apply it to a new Date object.



When I do that... I get the clients timezone date instead of the one I would like.



var time = "2018-12-30T20:00:00-05:00"
new Date(time)


I don't mind leveraging momentjs or any other library in JS but I am trying to do this in my front-end.



UPDATE



if the date returned from my backend has -05:00 as the offset... then when I create a date object in the front end... it should have the same offset



For example:



2018-12-31T10:00:00-05:00









share|improve this question

























  • Your question is a little vague because there is more than one way to interpret applying an offset to a date — you could convert it to a new absolute time, you could keep the absolute time the same, but apply a new offset, etc. It would help if you gave an example of a correct before and after date/time.

    – Mark Meyer
    Dec 30 '18 at 23:42











  • @MarkMeyer added an example

    – HeelMega
    Dec 30 '18 at 23:45











  • did you try to use ordinary way?

    – Jin
    Dec 30 '18 at 23:49











  • @Jin yes but it goes with the clients offset instead of using the -5 offset jsfiddle.net/f8hqwb1k

    – HeelMega
    Dec 30 '18 at 23:51













  • then what is your expected result? can you write an example? with your above text

    – Jin
    Dec 30 '18 at 23:54


















0















I have a datetime string returned from my backend like this:



2018-12-30T20:00:00-05:00


I am trying to get the offset from this datetime string and apply it to a new Date object.



When I do that... I get the clients timezone date instead of the one I would like.



var time = "2018-12-30T20:00:00-05:00"
new Date(time)


I don't mind leveraging momentjs or any other library in JS but I am trying to do this in my front-end.



UPDATE



if the date returned from my backend has -05:00 as the offset... then when I create a date object in the front end... it should have the same offset



For example:



2018-12-31T10:00:00-05:00









share|improve this question

























  • Your question is a little vague because there is more than one way to interpret applying an offset to a date — you could convert it to a new absolute time, you could keep the absolute time the same, but apply a new offset, etc. It would help if you gave an example of a correct before and after date/time.

    – Mark Meyer
    Dec 30 '18 at 23:42











  • @MarkMeyer added an example

    – HeelMega
    Dec 30 '18 at 23:45











  • did you try to use ordinary way?

    – Jin
    Dec 30 '18 at 23:49











  • @Jin yes but it goes with the clients offset instead of using the -5 offset jsfiddle.net/f8hqwb1k

    – HeelMega
    Dec 30 '18 at 23:51













  • then what is your expected result? can you write an example? with your above text

    – Jin
    Dec 30 '18 at 23:54
















0












0








0








I have a datetime string returned from my backend like this:



2018-12-30T20:00:00-05:00


I am trying to get the offset from this datetime string and apply it to a new Date object.



When I do that... I get the clients timezone date instead of the one I would like.



var time = "2018-12-30T20:00:00-05:00"
new Date(time)


I don't mind leveraging momentjs or any other library in JS but I am trying to do this in my front-end.



UPDATE



if the date returned from my backend has -05:00 as the offset... then when I create a date object in the front end... it should have the same offset



For example:



2018-12-31T10:00:00-05:00









share|improve this question
















I have a datetime string returned from my backend like this:



2018-12-30T20:00:00-05:00


I am trying to get the offset from this datetime string and apply it to a new Date object.



When I do that... I get the clients timezone date instead of the one I would like.



var time = "2018-12-30T20:00:00-05:00"
new Date(time)


I don't mind leveraging momentjs or any other library in JS but I am trying to do this in my front-end.



UPDATE



if the date returned from my backend has -05:00 as the offset... then when I create a date object in the front end... it should have the same offset



For example:



2018-12-31T10:00:00-05:00






javascript date datetime object momentjs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 30 '18 at 23:45







HeelMega

















asked Dec 30 '18 at 23:23









HeelMegaHeelMega

698




698













  • Your question is a little vague because there is more than one way to interpret applying an offset to a date — you could convert it to a new absolute time, you could keep the absolute time the same, but apply a new offset, etc. It would help if you gave an example of a correct before and after date/time.

    – Mark Meyer
    Dec 30 '18 at 23:42











  • @MarkMeyer added an example

    – HeelMega
    Dec 30 '18 at 23:45











  • did you try to use ordinary way?

    – Jin
    Dec 30 '18 at 23:49











  • @Jin yes but it goes with the clients offset instead of using the -5 offset jsfiddle.net/f8hqwb1k

    – HeelMega
    Dec 30 '18 at 23:51













  • then what is your expected result? can you write an example? with your above text

    – Jin
    Dec 30 '18 at 23:54





















  • Your question is a little vague because there is more than one way to interpret applying an offset to a date — you could convert it to a new absolute time, you could keep the absolute time the same, but apply a new offset, etc. It would help if you gave an example of a correct before and after date/time.

    – Mark Meyer
    Dec 30 '18 at 23:42











  • @MarkMeyer added an example

    – HeelMega
    Dec 30 '18 at 23:45











  • did you try to use ordinary way?

    – Jin
    Dec 30 '18 at 23:49











  • @Jin yes but it goes with the clients offset instead of using the -5 offset jsfiddle.net/f8hqwb1k

    – HeelMega
    Dec 30 '18 at 23:51













  • then what is your expected result? can you write an example? with your above text

    – Jin
    Dec 30 '18 at 23:54



















Your question is a little vague because there is more than one way to interpret applying an offset to a date — you could convert it to a new absolute time, you could keep the absolute time the same, but apply a new offset, etc. It would help if you gave an example of a correct before and after date/time.

– Mark Meyer
Dec 30 '18 at 23:42





Your question is a little vague because there is more than one way to interpret applying an offset to a date — you could convert it to a new absolute time, you could keep the absolute time the same, but apply a new offset, etc. It would help if you gave an example of a correct before and after date/time.

– Mark Meyer
Dec 30 '18 at 23:42













@MarkMeyer added an example

– HeelMega
Dec 30 '18 at 23:45





@MarkMeyer added an example

– HeelMega
Dec 30 '18 at 23:45













did you try to use ordinary way?

– Jin
Dec 30 '18 at 23:49





did you try to use ordinary way?

– Jin
Dec 30 '18 at 23:49













@Jin yes but it goes with the clients offset instead of using the -5 offset jsfiddle.net/f8hqwb1k

– HeelMega
Dec 30 '18 at 23:51







@Jin yes but it goes with the clients offset instead of using the -5 offset jsfiddle.net/f8hqwb1k

– HeelMega
Dec 30 '18 at 23:51















then what is your expected result? can you write an example? with your above text

– Jin
Dec 30 '18 at 23:54







then what is your expected result? can you write an example? with your above text

– Jin
Dec 30 '18 at 23:54














3 Answers
3






active

oldest

votes


















3














If you're willing to use moment you can easily pull the offset from the date/time with utcOffset. You can use the same function to apply the offset to the new date/time. Here are two moment objects that represent the same time, but with different offsets. This converts the second to the offset of the first without changing the absolute time:






var time = "2018-12-30T10:00:00-05:00"
let m = moment.parseZone(time)
let offset = m.utcOffset()
console.log("original: ", m.format(), "Offset:", offset)

// same time as m but -1 ofset
let m2 = moment.parseZone("2018-12-30T14:00:00-01:00")
console.log("m2 original: ", m2.format())

// change offset
m2.utcOffset(offset)
console.log("m2 converted: ", m2.format())

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>








share|improve this answer































    1














    Here is a very rough example of how to approach this with pure JS, for those that get here and don't want to use Moment JS:






    const d = new Date("2018-12-30T20:00:00-05:00");
    const epochTimeDate = d.getTime(); // Get milliseconds since Unix Epoch
    const localTZOffsetMilliseconds = d.getTimezoneOffset() * (60 * 1000); // Convert minutes to milliseconds
    const msCoefficient = (60 * 60 * 1000);
    const newTZOffsetHours = -3; // UTC -3

    const newTZTime = new Date(epochTimeDate - (-1*(newTZOffsetHours*msCoefficient))); // The -1 reverses the confusing behavior of the browser spec which is the opposite of the actual offset
    console.log(newTZTime.toISOString().replace(/T|Z/g,' ')+"(UTC "+newTZOffsetHours+")");





    The better way to output would be to implement your own function that displays the date using the getter functions for hours, minutes, etc. I'm not sure if the .toISOString() is standard but it works in Chrome.






    share|improve this answer


























    • I hear ISOString has cross browser compatibility issues but this is still a good answer

      – HeelMega
      Dec 31 '18 at 15:30











    • You don't need to mess around with milliseconds like that, just adjust the UTC minutes.

      – RobG
      Jan 1 at 4:50



















    1














    You need to get the timezone from the string, the convert it to an ECMAScript offset and use it to format a string with the required offset.



    There are already answers on SO to do the above, but here's an answer anyway.



    E.g.






    /* Returns offset, uses match to allow for decimal seconds in timestamp
    ** @param {string} s - ECMAScript formatted datetime string with offset
    ** in the format YYYY-MM-DDTHH:mm:ss+/-HH:mm or Z
    ** @returns {string} - offset part of string, i.e. +/-HH:mm or Z
    */
    function getOffset(s) {
    return offset = (s.match(/z$|[+-]dd:dd$/i) || )[0];
    }

    /* Convert offset in +/-HH:mm format or Z to ECMAScript offset
    ** @param {string} offset - in +/-HH:mm format or Z
    ** @returns {number} - ECMSCript offset in minutes, i.e. -ve east, +ve west
    */
    function offsetToMins(offset) {
    // Deal with Z or z
    if (/z/i.test(offset)) return 0;
    // Deal +/-HH:mm
    var sign = /^-/.test(offset)? '1':'-1';
    var [h, m] = offset.slice(-5).split(':');
    return sign * h * 60 + +m;
    }

    /* Format date with offset
    ** @param {Date} date - date to format
    ** @param {string} offset - ECMASCript offset string,
    ** e.g. -05:00, Z
    ** @returns {string} ISO 8601 formatted string with
    ** specified offset
    */
    function adjustToOffset(date, offset) {
    var o = offsetToMins(offset);
    var d = new Date(+date);
    d.setUTCMinutes(d.getUTCMinutes() - o);
    return d.toISOString().replace('Z', offset);
    }

    // Source string
    var s = '2018-12-30T20:00:00-05:00';

    // Get offset
    var offset = getOffset(s);

    // Make sure it's ok
    if (typeof offset == 'undefined') {
    console.log('offset not found');

    // Otherwise, show current time with specified offset
    } else {
    console.log(adjustToOffset(new Date(), offset));
    }





    Note that typical ISO 8601 offsets don't have a colon, i.e. they're usually ±HHmm.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53982238%2fget-offset-from-datetime-string-and-apply-to-a-new-date-object%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      If you're willing to use moment you can easily pull the offset from the date/time with utcOffset. You can use the same function to apply the offset to the new date/time. Here are two moment objects that represent the same time, but with different offsets. This converts the second to the offset of the first without changing the absolute time:






      var time = "2018-12-30T10:00:00-05:00"
      let m = moment.parseZone(time)
      let offset = m.utcOffset()
      console.log("original: ", m.format(), "Offset:", offset)

      // same time as m but -1 ofset
      let m2 = moment.parseZone("2018-12-30T14:00:00-01:00")
      console.log("m2 original: ", m2.format())

      // change offset
      m2.utcOffset(offset)
      console.log("m2 converted: ", m2.format())

      <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>








      share|improve this answer




























        3














        If you're willing to use moment you can easily pull the offset from the date/time with utcOffset. You can use the same function to apply the offset to the new date/time. Here are two moment objects that represent the same time, but with different offsets. This converts the second to the offset of the first without changing the absolute time:






        var time = "2018-12-30T10:00:00-05:00"
        let m = moment.parseZone(time)
        let offset = m.utcOffset()
        console.log("original: ", m.format(), "Offset:", offset)

        // same time as m but -1 ofset
        let m2 = moment.parseZone("2018-12-30T14:00:00-01:00")
        console.log("m2 original: ", m2.format())

        // change offset
        m2.utcOffset(offset)
        console.log("m2 converted: ", m2.format())

        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>








        share|improve this answer


























          3












          3








          3







          If you're willing to use moment you can easily pull the offset from the date/time with utcOffset. You can use the same function to apply the offset to the new date/time. Here are two moment objects that represent the same time, but with different offsets. This converts the second to the offset of the first without changing the absolute time:






          var time = "2018-12-30T10:00:00-05:00"
          let m = moment.parseZone(time)
          let offset = m.utcOffset()
          console.log("original: ", m.format(), "Offset:", offset)

          // same time as m but -1 ofset
          let m2 = moment.parseZone("2018-12-30T14:00:00-01:00")
          console.log("m2 original: ", m2.format())

          // change offset
          m2.utcOffset(offset)
          console.log("m2 converted: ", m2.format())

          <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>








          share|improve this answer













          If you're willing to use moment you can easily pull the offset from the date/time with utcOffset. You can use the same function to apply the offset to the new date/time. Here are two moment objects that represent the same time, but with different offsets. This converts the second to the offset of the first without changing the absolute time:






          var time = "2018-12-30T10:00:00-05:00"
          let m = moment.parseZone(time)
          let offset = m.utcOffset()
          console.log("original: ", m.format(), "Offset:", offset)

          // same time as m but -1 ofset
          let m2 = moment.parseZone("2018-12-30T14:00:00-01:00")
          console.log("m2 original: ", m2.format())

          // change offset
          m2.utcOffset(offset)
          console.log("m2 converted: ", m2.format())

          <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>








          var time = "2018-12-30T10:00:00-05:00"
          let m = moment.parseZone(time)
          let offset = m.utcOffset()
          console.log("original: ", m.format(), "Offset:", offset)

          // same time as m but -1 ofset
          let m2 = moment.parseZone("2018-12-30T14:00:00-01:00")
          console.log("m2 original: ", m2.format())

          // change offset
          m2.utcOffset(offset)
          console.log("m2 converted: ", m2.format())

          <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>





          var time = "2018-12-30T10:00:00-05:00"
          let m = moment.parseZone(time)
          let offset = m.utcOffset()
          console.log("original: ", m.format(), "Offset:", offset)

          // same time as m but -1 ofset
          let m2 = moment.parseZone("2018-12-30T14:00:00-01:00")
          console.log("m2 original: ", m2.format())

          // change offset
          m2.utcOffset(offset)
          console.log("m2 converted: ", m2.format())

          <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 31 '18 at 0:07









          Mark MeyerMark Meyer

          38.9k33160




          38.9k33160

























              1














              Here is a very rough example of how to approach this with pure JS, for those that get here and don't want to use Moment JS:






              const d = new Date("2018-12-30T20:00:00-05:00");
              const epochTimeDate = d.getTime(); // Get milliseconds since Unix Epoch
              const localTZOffsetMilliseconds = d.getTimezoneOffset() * (60 * 1000); // Convert minutes to milliseconds
              const msCoefficient = (60 * 60 * 1000);
              const newTZOffsetHours = -3; // UTC -3

              const newTZTime = new Date(epochTimeDate - (-1*(newTZOffsetHours*msCoefficient))); // The -1 reverses the confusing behavior of the browser spec which is the opposite of the actual offset
              console.log(newTZTime.toISOString().replace(/T|Z/g,' ')+"(UTC "+newTZOffsetHours+")");





              The better way to output would be to implement your own function that displays the date using the getter functions for hours, minutes, etc. I'm not sure if the .toISOString() is standard but it works in Chrome.






              share|improve this answer


























              • I hear ISOString has cross browser compatibility issues but this is still a good answer

                – HeelMega
                Dec 31 '18 at 15:30











              • You don't need to mess around with milliseconds like that, just adjust the UTC minutes.

                – RobG
                Jan 1 at 4:50
















              1














              Here is a very rough example of how to approach this with pure JS, for those that get here and don't want to use Moment JS:






              const d = new Date("2018-12-30T20:00:00-05:00");
              const epochTimeDate = d.getTime(); // Get milliseconds since Unix Epoch
              const localTZOffsetMilliseconds = d.getTimezoneOffset() * (60 * 1000); // Convert minutes to milliseconds
              const msCoefficient = (60 * 60 * 1000);
              const newTZOffsetHours = -3; // UTC -3

              const newTZTime = new Date(epochTimeDate - (-1*(newTZOffsetHours*msCoefficient))); // The -1 reverses the confusing behavior of the browser spec which is the opposite of the actual offset
              console.log(newTZTime.toISOString().replace(/T|Z/g,' ')+"(UTC "+newTZOffsetHours+")");





              The better way to output would be to implement your own function that displays the date using the getter functions for hours, minutes, etc. I'm not sure if the .toISOString() is standard but it works in Chrome.






              share|improve this answer


























              • I hear ISOString has cross browser compatibility issues but this is still a good answer

                – HeelMega
                Dec 31 '18 at 15:30











              • You don't need to mess around with milliseconds like that, just adjust the UTC minutes.

                – RobG
                Jan 1 at 4:50














              1












              1








              1







              Here is a very rough example of how to approach this with pure JS, for those that get here and don't want to use Moment JS:






              const d = new Date("2018-12-30T20:00:00-05:00");
              const epochTimeDate = d.getTime(); // Get milliseconds since Unix Epoch
              const localTZOffsetMilliseconds = d.getTimezoneOffset() * (60 * 1000); // Convert minutes to milliseconds
              const msCoefficient = (60 * 60 * 1000);
              const newTZOffsetHours = -3; // UTC -3

              const newTZTime = new Date(epochTimeDate - (-1*(newTZOffsetHours*msCoefficient))); // The -1 reverses the confusing behavior of the browser spec which is the opposite of the actual offset
              console.log(newTZTime.toISOString().replace(/T|Z/g,' ')+"(UTC "+newTZOffsetHours+")");





              The better way to output would be to implement your own function that displays the date using the getter functions for hours, minutes, etc. I'm not sure if the .toISOString() is standard but it works in Chrome.






              share|improve this answer















              Here is a very rough example of how to approach this with pure JS, for those that get here and don't want to use Moment JS:






              const d = new Date("2018-12-30T20:00:00-05:00");
              const epochTimeDate = d.getTime(); // Get milliseconds since Unix Epoch
              const localTZOffsetMilliseconds = d.getTimezoneOffset() * (60 * 1000); // Convert minutes to milliseconds
              const msCoefficient = (60 * 60 * 1000);
              const newTZOffsetHours = -3; // UTC -3

              const newTZTime = new Date(epochTimeDate - (-1*(newTZOffsetHours*msCoefficient))); // The -1 reverses the confusing behavior of the browser spec which is the opposite of the actual offset
              console.log(newTZTime.toISOString().replace(/T|Z/g,' ')+"(UTC "+newTZOffsetHours+")");





              The better way to output would be to implement your own function that displays the date using the getter functions for hours, minutes, etc. I'm not sure if the .toISOString() is standard but it works in Chrome.






              const d = new Date("2018-12-30T20:00:00-05:00");
              const epochTimeDate = d.getTime(); // Get milliseconds since Unix Epoch
              const localTZOffsetMilliseconds = d.getTimezoneOffset() * (60 * 1000); // Convert minutes to milliseconds
              const msCoefficient = (60 * 60 * 1000);
              const newTZOffsetHours = -3; // UTC -3

              const newTZTime = new Date(epochTimeDate - (-1*(newTZOffsetHours*msCoefficient))); // The -1 reverses the confusing behavior of the browser spec which is the opposite of the actual offset
              console.log(newTZTime.toISOString().replace(/T|Z/g,' ')+"(UTC "+newTZOffsetHours+")");





              const d = new Date("2018-12-30T20:00:00-05:00");
              const epochTimeDate = d.getTime(); // Get milliseconds since Unix Epoch
              const localTZOffsetMilliseconds = d.getTimezoneOffset() * (60 * 1000); // Convert minutes to milliseconds
              const msCoefficient = (60 * 60 * 1000);
              const newTZOffsetHours = -3; // UTC -3

              const newTZTime = new Date(epochTimeDate - (-1*(newTZOffsetHours*msCoefficient))); // The -1 reverses the confusing behavior of the browser spec which is the opposite of the actual offset
              console.log(newTZTime.toISOString().replace(/T|Z/g,' ')+"(UTC "+newTZOffsetHours+")");






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 31 '18 at 1:16

























              answered Dec 31 '18 at 1:00









              Alex WAlex W

              27.8k76681




              27.8k76681













              • I hear ISOString has cross browser compatibility issues but this is still a good answer

                – HeelMega
                Dec 31 '18 at 15:30











              • You don't need to mess around with milliseconds like that, just adjust the UTC minutes.

                – RobG
                Jan 1 at 4:50



















              • I hear ISOString has cross browser compatibility issues but this is still a good answer

                – HeelMega
                Dec 31 '18 at 15:30











              • You don't need to mess around with milliseconds like that, just adjust the UTC minutes.

                – RobG
                Jan 1 at 4:50

















              I hear ISOString has cross browser compatibility issues but this is still a good answer

              – HeelMega
              Dec 31 '18 at 15:30





              I hear ISOString has cross browser compatibility issues but this is still a good answer

              – HeelMega
              Dec 31 '18 at 15:30













              You don't need to mess around with milliseconds like that, just adjust the UTC minutes.

              – RobG
              Jan 1 at 4:50





              You don't need to mess around with milliseconds like that, just adjust the UTC minutes.

              – RobG
              Jan 1 at 4:50











              1














              You need to get the timezone from the string, the convert it to an ECMAScript offset and use it to format a string with the required offset.



              There are already answers on SO to do the above, but here's an answer anyway.



              E.g.






              /* Returns offset, uses match to allow for decimal seconds in timestamp
              ** @param {string} s - ECMAScript formatted datetime string with offset
              ** in the format YYYY-MM-DDTHH:mm:ss+/-HH:mm or Z
              ** @returns {string} - offset part of string, i.e. +/-HH:mm or Z
              */
              function getOffset(s) {
              return offset = (s.match(/z$|[+-]dd:dd$/i) || )[0];
              }

              /* Convert offset in +/-HH:mm format or Z to ECMAScript offset
              ** @param {string} offset - in +/-HH:mm format or Z
              ** @returns {number} - ECMSCript offset in minutes, i.e. -ve east, +ve west
              */
              function offsetToMins(offset) {
              // Deal with Z or z
              if (/z/i.test(offset)) return 0;
              // Deal +/-HH:mm
              var sign = /^-/.test(offset)? '1':'-1';
              var [h, m] = offset.slice(-5).split(':');
              return sign * h * 60 + +m;
              }

              /* Format date with offset
              ** @param {Date} date - date to format
              ** @param {string} offset - ECMASCript offset string,
              ** e.g. -05:00, Z
              ** @returns {string} ISO 8601 formatted string with
              ** specified offset
              */
              function adjustToOffset(date, offset) {
              var o = offsetToMins(offset);
              var d = new Date(+date);
              d.setUTCMinutes(d.getUTCMinutes() - o);
              return d.toISOString().replace('Z', offset);
              }

              // Source string
              var s = '2018-12-30T20:00:00-05:00';

              // Get offset
              var offset = getOffset(s);

              // Make sure it's ok
              if (typeof offset == 'undefined') {
              console.log('offset not found');

              // Otherwise, show current time with specified offset
              } else {
              console.log(adjustToOffset(new Date(), offset));
              }





              Note that typical ISO 8601 offsets don't have a colon, i.e. they're usually ±HHmm.






              share|improve this answer




























                1














                You need to get the timezone from the string, the convert it to an ECMAScript offset and use it to format a string with the required offset.



                There are already answers on SO to do the above, but here's an answer anyway.



                E.g.






                /* Returns offset, uses match to allow for decimal seconds in timestamp
                ** @param {string} s - ECMAScript formatted datetime string with offset
                ** in the format YYYY-MM-DDTHH:mm:ss+/-HH:mm or Z
                ** @returns {string} - offset part of string, i.e. +/-HH:mm or Z
                */
                function getOffset(s) {
                return offset = (s.match(/z$|[+-]dd:dd$/i) || )[0];
                }

                /* Convert offset in +/-HH:mm format or Z to ECMAScript offset
                ** @param {string} offset - in +/-HH:mm format or Z
                ** @returns {number} - ECMSCript offset in minutes, i.e. -ve east, +ve west
                */
                function offsetToMins(offset) {
                // Deal with Z or z
                if (/z/i.test(offset)) return 0;
                // Deal +/-HH:mm
                var sign = /^-/.test(offset)? '1':'-1';
                var [h, m] = offset.slice(-5).split(':');
                return sign * h * 60 + +m;
                }

                /* Format date with offset
                ** @param {Date} date - date to format
                ** @param {string} offset - ECMASCript offset string,
                ** e.g. -05:00, Z
                ** @returns {string} ISO 8601 formatted string with
                ** specified offset
                */
                function adjustToOffset(date, offset) {
                var o = offsetToMins(offset);
                var d = new Date(+date);
                d.setUTCMinutes(d.getUTCMinutes() - o);
                return d.toISOString().replace('Z', offset);
                }

                // Source string
                var s = '2018-12-30T20:00:00-05:00';

                // Get offset
                var offset = getOffset(s);

                // Make sure it's ok
                if (typeof offset == 'undefined') {
                console.log('offset not found');

                // Otherwise, show current time with specified offset
                } else {
                console.log(adjustToOffset(new Date(), offset));
                }





                Note that typical ISO 8601 offsets don't have a colon, i.e. they're usually ±HHmm.






                share|improve this answer


























                  1












                  1








                  1







                  You need to get the timezone from the string, the convert it to an ECMAScript offset and use it to format a string with the required offset.



                  There are already answers on SO to do the above, but here's an answer anyway.



                  E.g.






                  /* Returns offset, uses match to allow for decimal seconds in timestamp
                  ** @param {string} s - ECMAScript formatted datetime string with offset
                  ** in the format YYYY-MM-DDTHH:mm:ss+/-HH:mm or Z
                  ** @returns {string} - offset part of string, i.e. +/-HH:mm or Z
                  */
                  function getOffset(s) {
                  return offset = (s.match(/z$|[+-]dd:dd$/i) || )[0];
                  }

                  /* Convert offset in +/-HH:mm format or Z to ECMAScript offset
                  ** @param {string} offset - in +/-HH:mm format or Z
                  ** @returns {number} - ECMSCript offset in minutes, i.e. -ve east, +ve west
                  */
                  function offsetToMins(offset) {
                  // Deal with Z or z
                  if (/z/i.test(offset)) return 0;
                  // Deal +/-HH:mm
                  var sign = /^-/.test(offset)? '1':'-1';
                  var [h, m] = offset.slice(-5).split(':');
                  return sign * h * 60 + +m;
                  }

                  /* Format date with offset
                  ** @param {Date} date - date to format
                  ** @param {string} offset - ECMASCript offset string,
                  ** e.g. -05:00, Z
                  ** @returns {string} ISO 8601 formatted string with
                  ** specified offset
                  */
                  function adjustToOffset(date, offset) {
                  var o = offsetToMins(offset);
                  var d = new Date(+date);
                  d.setUTCMinutes(d.getUTCMinutes() - o);
                  return d.toISOString().replace('Z', offset);
                  }

                  // Source string
                  var s = '2018-12-30T20:00:00-05:00';

                  // Get offset
                  var offset = getOffset(s);

                  // Make sure it's ok
                  if (typeof offset == 'undefined') {
                  console.log('offset not found');

                  // Otherwise, show current time with specified offset
                  } else {
                  console.log(adjustToOffset(new Date(), offset));
                  }





                  Note that typical ISO 8601 offsets don't have a colon, i.e. they're usually ±HHmm.






                  share|improve this answer













                  You need to get the timezone from the string, the convert it to an ECMAScript offset and use it to format a string with the required offset.



                  There are already answers on SO to do the above, but here's an answer anyway.



                  E.g.






                  /* Returns offset, uses match to allow for decimal seconds in timestamp
                  ** @param {string} s - ECMAScript formatted datetime string with offset
                  ** in the format YYYY-MM-DDTHH:mm:ss+/-HH:mm or Z
                  ** @returns {string} - offset part of string, i.e. +/-HH:mm or Z
                  */
                  function getOffset(s) {
                  return offset = (s.match(/z$|[+-]dd:dd$/i) || )[0];
                  }

                  /* Convert offset in +/-HH:mm format or Z to ECMAScript offset
                  ** @param {string} offset - in +/-HH:mm format or Z
                  ** @returns {number} - ECMSCript offset in minutes, i.e. -ve east, +ve west
                  */
                  function offsetToMins(offset) {
                  // Deal with Z or z
                  if (/z/i.test(offset)) return 0;
                  // Deal +/-HH:mm
                  var sign = /^-/.test(offset)? '1':'-1';
                  var [h, m] = offset.slice(-5).split(':');
                  return sign * h * 60 + +m;
                  }

                  /* Format date with offset
                  ** @param {Date} date - date to format
                  ** @param {string} offset - ECMASCript offset string,
                  ** e.g. -05:00, Z
                  ** @returns {string} ISO 8601 formatted string with
                  ** specified offset
                  */
                  function adjustToOffset(date, offset) {
                  var o = offsetToMins(offset);
                  var d = new Date(+date);
                  d.setUTCMinutes(d.getUTCMinutes() - o);
                  return d.toISOString().replace('Z', offset);
                  }

                  // Source string
                  var s = '2018-12-30T20:00:00-05:00';

                  // Get offset
                  var offset = getOffset(s);

                  // Make sure it's ok
                  if (typeof offset == 'undefined') {
                  console.log('offset not found');

                  // Otherwise, show current time with specified offset
                  } else {
                  console.log(adjustToOffset(new Date(), offset));
                  }





                  Note that typical ISO 8601 offsets don't have a colon, i.e. they're usually ±HHmm.






                  /* Returns offset, uses match to allow for decimal seconds in timestamp
                  ** @param {string} s - ECMAScript formatted datetime string with offset
                  ** in the format YYYY-MM-DDTHH:mm:ss+/-HH:mm or Z
                  ** @returns {string} - offset part of string, i.e. +/-HH:mm or Z
                  */
                  function getOffset(s) {
                  return offset = (s.match(/z$|[+-]dd:dd$/i) || )[0];
                  }

                  /* Convert offset in +/-HH:mm format or Z to ECMAScript offset
                  ** @param {string} offset - in +/-HH:mm format or Z
                  ** @returns {number} - ECMSCript offset in minutes, i.e. -ve east, +ve west
                  */
                  function offsetToMins(offset) {
                  // Deal with Z or z
                  if (/z/i.test(offset)) return 0;
                  // Deal +/-HH:mm
                  var sign = /^-/.test(offset)? '1':'-1';
                  var [h, m] = offset.slice(-5).split(':');
                  return sign * h * 60 + +m;
                  }

                  /* Format date with offset
                  ** @param {Date} date - date to format
                  ** @param {string} offset - ECMASCript offset string,
                  ** e.g. -05:00, Z
                  ** @returns {string} ISO 8601 formatted string with
                  ** specified offset
                  */
                  function adjustToOffset(date, offset) {
                  var o = offsetToMins(offset);
                  var d = new Date(+date);
                  d.setUTCMinutes(d.getUTCMinutes() - o);
                  return d.toISOString().replace('Z', offset);
                  }

                  // Source string
                  var s = '2018-12-30T20:00:00-05:00';

                  // Get offset
                  var offset = getOffset(s);

                  // Make sure it's ok
                  if (typeof offset == 'undefined') {
                  console.log('offset not found');

                  // Otherwise, show current time with specified offset
                  } else {
                  console.log(adjustToOffset(new Date(), offset));
                  }





                  /* Returns offset, uses match to allow for decimal seconds in timestamp
                  ** @param {string} s - ECMAScript formatted datetime string with offset
                  ** in the format YYYY-MM-DDTHH:mm:ss+/-HH:mm or Z
                  ** @returns {string} - offset part of string, i.e. +/-HH:mm or Z
                  */
                  function getOffset(s) {
                  return offset = (s.match(/z$|[+-]dd:dd$/i) || )[0];
                  }

                  /* Convert offset in +/-HH:mm format or Z to ECMAScript offset
                  ** @param {string} offset - in +/-HH:mm format or Z
                  ** @returns {number} - ECMSCript offset in minutes, i.e. -ve east, +ve west
                  */
                  function offsetToMins(offset) {
                  // Deal with Z or z
                  if (/z/i.test(offset)) return 0;
                  // Deal +/-HH:mm
                  var sign = /^-/.test(offset)? '1':'-1';
                  var [h, m] = offset.slice(-5).split(':');
                  return sign * h * 60 + +m;
                  }

                  /* Format date with offset
                  ** @param {Date} date - date to format
                  ** @param {string} offset - ECMASCript offset string,
                  ** e.g. -05:00, Z
                  ** @returns {string} ISO 8601 formatted string with
                  ** specified offset
                  */
                  function adjustToOffset(date, offset) {
                  var o = offsetToMins(offset);
                  var d = new Date(+date);
                  d.setUTCMinutes(d.getUTCMinutes() - o);
                  return d.toISOString().replace('Z', offset);
                  }

                  // Source string
                  var s = '2018-12-30T20:00:00-05:00';

                  // Get offset
                  var offset = getOffset(s);

                  // Make sure it's ok
                  if (typeof offset == 'undefined') {
                  console.log('offset not found');

                  // Otherwise, show current time with specified offset
                  } else {
                  console.log(adjustToOffset(new Date(), offset));
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 1 at 4:49









                  RobGRobG

                  98.7k19110146




                  98.7k19110146






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53982238%2fget-offset-from-datetime-string-and-apply-to-a-new-date-object%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      MongoDB - Not Authorized To Execute Command

                      How to fix TextFormField cause rebuild widget in Flutter

                      Npm cannot find a required file even through it is in the searched directory