javascript 使用javascript将日期字符串转换为UTC+0530格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4990367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:35:50  来源:igfitidea点击:

Converting a date string into UTC+0530 format using javascript

javascriptdatetimestring-formatting

提问by Akshay

I have a date in the format 14-Feb-2011, but I want to convert it into the format Mon Feb 14 10:13:50 UTC+0530 2011. How Can I achieve this?

我有格式的日期14-Feb-2011,但我想将其转换为格式Mon Feb 14 10:13:50 UTC+0530 2011。我怎样才能做到这一点?

回答by Shekhar_Pro

Using new Date(Date.UTC(year, month, day, hour, minute, second))you can create a Date-object from a specific UTC time.

使用new Date(Date.UTC(year, month, day, hour, minute, second))您可以从特定的 UTC 时间创建日期对象。

I tried this code and it returned proper date (In Indian Locale)

我试过这段代码,它返回了正确的日期(在印度语言环境中)

var d=Date.parse("14,Feb,2011");
document.write(new Date(d));

Output:

输出:

Mon Feb 14 2011 00:00:00 GMT+0530 (India Standard Time) .



这是在不同时区之间转换的示例。

<html>
<body>

<script type="text/javascript">

//Set you offset here like +5.5 for IST
var offsetIST = 5.5;


//Set you offset here like -8 for PST
var offsetPST = -8;

//Create a new date from the Given string
var d=new Date(Date.parse("14,Feb,2011"));

//To convert to UTC datetime by subtracting the current Timezone offset
var utcdate =  new Date(d.getTime() + (d.getTimezoneOffset()*60000));

//Then cinver the UTS date to the required time zone offset like back to 5.5 for IST
var istdate =  new Date(utcdate.getTime() - ((-offsetIST*60)*60000));

//Then cinver the UTS date to the required time zone offset like back to -8 for PST (Canada US)
var pstdate=  new Date(utcdate.getTime() - ((-offsetPST*60)*60000));

document.write(d);
document.write("<br/>");
document.write(utcdate);
document.write("<br/>");
document.write(istdate);
document.write("<br/>");
document.write(pstdate);
</script>

</body>
</html>

Output:

输出:

Mon Feb 14 2011 00:00:00 GMT+0530 (India Standard Time)
Sun Feb 13 2011 18:30:00 GMT+0530 (India Standard Time)
Mon Feb 14 2011 00:00:00 GMT+0530 (India Standard Time)
Sun Feb 13 2011 10:30:00 GMT+0530 (India Standard Time) 

Its writing IST every where because new Date() always show date as local timezone (which is IST for me) but above datetime are actually Original, UTC, IST, PSTrespectively.

它在任何地方都写 IST,因为 new Date() 总是将日期显示为本地时区(对我来说是 IST),但在日期时间之上实际上分别是OriginalUTCISTPST

回答by tamilnad

var d = new Date("14-Feb-2011");

this will give an output of Mon Feb 14 2011 00:00:00 GMT-0500 (Eastern Standard Time)

这将给出 Mon Feb 14 2011 00:00:00 GMT-0500(东部标准时间)的输出