javascript 使用javascript从日期时间中提取时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15546292/
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
extract time from datetime using javascript
提问by Psl
how can i extract time from datetime format.
如何从日期时间格式中提取时间。
my datetime format is given below.
我的日期时间格式如下。
var datetime =2000-01-01 01:00:00 UTC;
I only want to get the time 01.00
as 01
我只想要得到的时间01.00
为01
回答by Andrew
Date.prototype.toLocaleTimeString() Returns a string with a locality sensitive representation of the time portion of this date based on system settings.
Date.prototype.toLocaleTimeString() 根据系统设置返回一个字符串,该字符串具有该日期时间部分的位置敏感表示。
var time = datetime.toLocaleTimeString();
Update:
更新:
The new locales and options arguments let applications specify the language whose formatting conventions should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.
新的语言环境和选项参数让应用程序指定应使用其格式约定的语言并自定义函数的行为。在忽略语言环境和选项参数的旧实现中,使用的语言环境和返回的字符串形式完全取决于实现。
// Depending on timezone, your results will vary
var event = new Date('August 19, 1975 23:15:30 GMT+00:00');
console.log(event.toLocaleTimeString('en-US'));
// expected output: 1:15:30 AM
console.log(event.toLocaleTimeString('it-IT'));
// expected output: 01:15:30
回答by subodh
What about these methods
这些方法呢
For example:
例如:
var d = new Date();
var n = d.getHours();
Edited
已编辑
Return the hour, according to universal time:
根据世界时间返回小时:
Example:
例子:
var d = new Date();
var n = d.getUTCHours();
回答by Mark Walters
As an alternative if you want to get the time from a string -
作为替代,如果您想从字符串中获取时间 -
var datetime ="2000-01-01 01:00:00 UTC";
var myTime = datetime.substr(11, 2);
alert(myTime) //01
回答by George Moik
回答by Anujith
回答by chungtinhlakho
var date1 = new Date(1945,10,20, 17,30)
var date2 = new Date(1970,1,8, 12,00)
console.log(date1.getHours() - 8 + (date1.getMinutes()/60))
console.log(date2.getHours() - 8 + (date2.getMinutes()/60))
回答by Bergi
Assuming you have a Date
objectlike
假设你有一个Date
对象像
var datetime = new Date("2000-01-01 01:00:00 UTC"); // might not parse correctly in every engine
// or
var datetime = new Date(Date.UTC(2000, 0, 1, 1, 0, 0));
then use the getUTCHours
method:
然后使用getUTCHours
方法:
datetime.getUTCHours(); // 1
回答by Code L?ver
Use the following code:
使用以下代码:
var datetime = "2000-01-01 01:00:00 UTC";
var dt = new Date(datetime);
var hr = dt.getUTCHours();
if(hr > 12) {
hr -= 12;
}
alert(hr);