Any way to parse a time string using Moment.js but ignore timezone info?

前端 未结 10 1564
深忆病人
深忆病人 2020-12-30 01:56

Given the volume of Timezone questions, I would have thought to be able to find the answer to this issue, but haven\'t had any success.

Is there a way using mo

相关标签:
10条回答
  • 2020-12-30 02:29

    Momentjs default logic will format the given time with local timezone. To format original date, I wrote a function:

    https://github.com/moment/moment/issues/2788#issuecomment-321950638

    0 讨论(0)
  • 2020-12-30 02:30

    I know I'm late to the party, I had the same question and my searches didn't bring me any closer. I broke down and read the documentation and there is an option in moment for a String + Format:

    String + Format docs

    moment(String, String);

    moment(String, String, String);

    moment(String, String, Boolean);

    moment(String, String, String, Boolean);

    and more words, then this:

    Unless you specify a time zone offset, parsing a string will create a date in the current time zone.

    moment("2010-10-20 4:30",       "YYYY-MM-DD HH:mm");   // parsed as 4:30 local time
    moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z"); // parsed as 4:30 UTC
    

    The part that gave me pause was the example that was used to parse local time omitted the +0000, which lead me to think the input string needed to have that removed, but it doesn't.

    example:

    var time = "2012-12-31T00:00:00+0000";
    var x = moment(time); // Sun Dec 30 2012 19:00:00 GMT-0500
    var y = moment(time,'YYYY-MM-DD'); //Mon Dec 31 2012 00:00:00 GMT-0500
    
    0 讨论(0)
  • 2020-12-30 02:32

    The best way is to use:

    dt = moment("Wed Sep 16 2015 18:31:00 GMT-0400", "ffffd MMM DD YYYY HH:mm:ss GMT-0400",true);
    

    And to display convert again to desired timezone:

     dt.utcOffset("-04:00").toString()
     output > Wed Sep 16 2015 18:31:00 GMT-0400
    
    0 讨论(0)
  • 2020-12-30 02:33

    I solved this by supplying a format as the second argument, and using Moment's method of escaping characters, and wrapped square brackets around the timezone.

    moment("2016-01-01T05:00:00-05:00", "YYYY-MM-DDTHH:mm:ss[Z]").startOf("hour").format()
    

    This will still create moment objects using your local time zone, but it won't do any sort of auto-timezone calculation. So the above example will give you 5am regardless of timezone supplied.

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