[英]convert string date and time to utc based on timezone using moment
am using moment in nodejs server to convert local time from frontend to utc.我在 nodejs 服务器中使用 moment 将本地时间从前端转换为 utc。
my time format is date = '10-07-2020 08:45 PM'
in string format.我的时间格式是字符串格式的
date = '10-07-2020 08:45 PM'
。 When i use moment(date).format()
its converting format to this 2020-10-07 20:45:00+05:30
timezone is adding based on server and i have timezone = '+4:00'
this is my local timezone.当我使用
moment(date).format()
它的转换格式为这个2020-10-07 20:45:00+05:30
时区是基于服务器添加的,我有timezone = '+4:00'
这是我的当地时区。 I would like to convert my date string to UTC based on the timezone
field not based on the server timezone.我想根据
timezone
字段而不是基于服务器时区将我的日期字符串转换为 UTC。 How can I do this?我怎样才能做到这一点?
I tried the following methods but am not getting a proper solution我尝试了以下方法,但没有得到正确的解决方案
moment.utc(moment(date).utcOffset(timezone)).format('YYYY-MM-DD HH:mm:ss')
Anyone Please suggest任何人请建议
You can use moment-timezone to create a date from a string and a certain timezone.您可以使用moment-timezone从字符串和特定时区创建日期。 In order to do that you need to specify your format and the corresponding timezone.
为此,您需要指定格式和相应的时区。 Something like this:
像这样的东西:
const date = moment.tz("10-07-2020 08:45 pm", "MD-YYYY hh:mm a", "Europe/Samara"); console.log(date.toISOString());
<script src="https://momentjs.com/downloads/moment.min.js"></script> <script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>
Instead of moment, perhaps use intl DateTimeFormat ?而不是瞬间,也许使用intl DateTimeFormat ?
Here are some possibilities这里有一些可能性
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', }; const date = new Date('10-07-2020 08:45 PM') console.log(date) options.timeZone = 'Europe/Ulyanovsk'; options.timeZoneName = 'short'; console.log(new Intl.DateTimeFormat('en-US', options).format(date));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.