0

I am trying to get the date with timezone as TIME_ZONE = 'Asia/Shanghai'. Below the script returns the UTC time. How to convert the date as the local date?

    <script>
        var today = new Date();
        today = new Date(today.setDate(today.getDate() + 1)).toISOString().split('T')[0];
        document.getElementsByName("pickup_date")[0].setAttribute('min', today);
    </script>

  <form method="POST">
       <div>
            <label for="s2">pickup_date</label>
            <input type = 'date'  name='pickup_date' required>
         <br /><br />
        </div>
  </form>


var today = new Date();
hr=today.getHours()  #this returns the UTC date and time. I need local date and time
console.log(today);

UPDATE:

  1. actually, I have a form which needs user to input date, and this date must exclude today and past dates. Due to time difference between UTC and Beijing Time(local time/browser time), the update of excluding date will lag behind the actual local date, in 8 hours.

  2. I just found that in mobile phone browser like safari, the fobbidden date can still be chosen. how to make sure it works on mobile phone browser?

DarkBee
  • 16,592
  • 6
  • 46
  • 58
Jack
  • 1,339
  • 1
  • 12
  • 31
  • Does this answer your question? [Convert UTC date time to local date time](https://stackoverflow.com/questions/6525538/convert-utc-date-time-to-local-date-time) – K.K Designs Jan 09 '22 at 19:08
  • I read this post and tried a number of solution. unfortunately I could not find it working. would be appreciate for direct solution to my case – Jack Jan 09 '22 at 19:12
  • 1
    Please show your *exact* expected output. If you want a timestamp as string in the format `yyyy-MM-ddTHH:mm:ss` but with localtime, unfortunately you will either have to create such a string yourself or use some external library. `Date.toISOString()` is defined to return the time as UTC time + timezone offset. – derpirscher Jan 09 '22 at 19:56
  • @derpirscher— *toISOString* always returns UTC, there is not offset. ;-) – RobG Jan 10 '22 at 03:35
  • The question is unclear. You can set the timezone of the output timestamp using *toLocaleString*'s *timeZone* option. However, you then ask "*How to convert the date as the local date*", when there is no need to set the timezone at all, the non–UTC Date methods will return local values based on the host system's settings, including for timezone offset. So what are you actually asking for help with? – RobG Jan 10 '22 at 03:38

1 Answers1

0

The toLocaleString function can be used for the localization of time. More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

var time = new Date();
var localTimeStr = time.toLocaleString('en-US', { timeZone: 'Asia/Shanghai' });
alert(localTimeStr)
Amirreza Noori
  • 1,456
  • 1
  • 6
  • 20