Javascript 如何将小时、分钟、秒设置为格林威治标准时间的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25663538/
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
How to set Hours,minutes,seconds to Date which is in GMT
提问by Arepalli Praveenkumar
I have Date Object ,I wanted to clear HOUR,MINUTE and SECONDS from My Date.Please help me how to do it in Javascript. Am i doing wrong ?
我有日期对象,我想从我的日期中清除 HOUR、MINUTE 和 SECONDS。请帮助我如何在 Javascript 中执行此操作。我做错了吗?
var date = Date("Fri, 26 Sep 2014 18:30:00 GMT");
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
Expected result is
预期结果是
Fri, 26 Sep 2014 00:00:00 GMT
How Do I achieve ?
我如何实现?
回答by Manjar
You can use this:
你可以使用这个:
// Like Fri, 26 Sep 2014 18:30:00 GMT
var today = new Date();
var myToday = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);
Recreate the Date object with constructor using the actual date.
使用实际日期通过构造函数重新创建 Date 对象。
回答by Afsa
According to MDNthe setHoursfunction actually takes additional optional parameters to set both minutes, seconds and milliseconds. Hence we may simply write
根据MDN,该setHours函数实际上需要额外的可选参数来设置分钟、秒和毫秒。因此我们可以简单地写
// dateString is for example "Fri, 26 Sep 2014 18:30:00 GMT"
function getFormattedDate(dateString) {
var date = new Date(dateString);
date.setHours(0, 0, 0); // Set hours, minutes and seconds
return date.toString();
}
回答by Alex Hoppen
To parse the date into JavaScript simply use
要将日期解析为 JavaScript,只需使用
var date = new Date("Fri, 26 Sep 2014 18:30:00 GMT”);
And then set Hours, Minutes and seconds to 0 with the following lines
然后使用以下几行将小时、分钟和秒设置为 0
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.toString()now returns your desired date
date.toString()现在返回您想要的日期

