Create a Date with a set timezone without using a string representation

前端 未结 23 1485
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 01:48

I have a web page with three dropdowns for day, month and year. If I use the JavaScript Date constructor that takes numbers, then I get a Date obje

23条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 02:03

    The easiest way that I have found to get the correct date is using datejs.

    http://www.datejs.com/

    I get my dates via Ajax in this format as a string: '2016-01-12T00:00:00'

    var yourDateString = '2016-01-12T00:00:00';
    var yourDate = new Date(yourDateString);
    console.log(yourDate);
    if (yourDate.getTimezoneOffset() > 0){
        yourDate = new Date(yourDateString).addMinutes(yourDate.getTimezoneOffset());
    }
    console.log(yourDate);
    

    Console will read:

    Mon Jan 11 2016 19:00:00 GMT-0500 (Eastern Standard Time)

    Tue Jan 12 2016 00:00:00 GMT-0500 (Eastern Standard Time)

    https://jsfiddle.net/vp1ena7b/3/

    The 'addMinutes' comes from datejs, you could probably do this in pure js on your own, but I already had datejs in my project so I found a way to use it to get the correct dates.

    I thought that this might help someone...

提交回复
热议问题