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

3
我有一个日期,格式为14-Feb-2011,但我想将其转换为格式Mon Feb 14 10:13:50 UTC+0530 2011。我该如何实现?

你是在使用JavaScript库还是原生JavaScript? - erlando
我认为这篇文章会对你有所帮助:如何在JavaScript中使用格式规范将字符串转换为日期时间? - Marat Faskhiev
2个回答

3
使用new Date(Date.UTC(year, month, day, hour, minute, second))可以从特定的UTC时间创建Date对象。
我尝试了这段代码,它返回了正确的日期(在印度本地)。
var d=Date.parse("14,Feb,2011");
document.write(new Date(d));

输出:

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>

输出:

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) 

因为 new Date() 总是显示本地时区的日期(对我来说是IST),所以 IST 在这里随处可见,但上面的日期实际上分别是原始时间协调世界时印度标准时间太平洋标准时间


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

这将输出: 2011年2月14日 星期一 00:00:00 GMT-0500(东部标准时间)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接