简体   繁体   English

使用javascript或momentjs将UTC时间仅转换为本地时间(无日期)

[英]Convert UTC time ONLY to local time ONLY (without date) using javascript or momentjs

I am fetching a string from database which is in a 24hr format and is stored in UTC time. 我正在从数据库中获取一个24小时格式的字符串,该字符串以UTC时间存储。 For example "18:00:00". 例如“ 18:00:00”。 I would want this time to be converted into local time only (no date is required), wherever the time zone may be and display it in 12hr format. 我希望将此时间仅转换为本地时间(不需要日期),无论时区在哪里,并以12小时格式显示。 For example, if the timezone is Australian Eastern Standard Time, I have to find out the time difference which is 11 hrs ahead of UTC time and display it as "05:00 AM" and also do the vice versa of local time only into UTC time only (no date is required) so that I can save it back to database. 例如,如果时区是澳大利亚东部标准时间,则我必须找出比UTC时间早11小时的时差,并将其显示为“ 05:00 AM”,并且仅将当地时间反过来才适用于UTC仅时间(不需要日期),这样我可以将其保存回数据库。 I have searched a lot for it but everyone mentions about converting date object from UTC to local or vice versa but not for time only. 我为此进行了很多搜索,但每个人都提到将日期对象从UTC转换为本地或反之亦然,而不仅仅是时间。 Please help me out with this. 这个你能帮我吗。

 let utcTime = "18:00:00"; let utcText = moment(utcTime,'HH:mm').format("HH:mm"); let local = moment.utc(utcTime,'HH:mm').local().format("hh:mm A"); let localTime = local;//setting local time let utc = moment(localTime,'hh:mm A').utc().format("HH:mm"); $("#utc").html(utcText + " (UTC Time)"); $("#local").html(local + " (Local Time)"); $("#utc1").html(localTime + " (Local Time1)"); $("#local1").html(utc + " (UTC Time1)"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.js"></script> <div id="utc"></div> <div id="local"></div> <div id="utc1"></div> <div id="local1"></div> 

Create a moment object using time and type , then convert to local timezone using local() 使用time和type创建一个力矩对象,然后使用local()转换为本地时区

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM