[英]Using regular expression, is there any other way in Javascript to extract date from string having time zone
I'm using regular expression to extract date and time information from a given string. 我正在使用正则表达式从给定的字符串中提取日期和时间信息。
2006-08-15T00:00:00+05:30
I'm new to regular expression and the way I'm doing it is as follows: 我是正则表达式的新手,其执行方式如下:
(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})
I know that there may be some better way to do this. 我知道可能会有更好的方法来做到这一点。 So, please if anybody has any knowledge on this topic please share and explain. 因此,如果有人对此主题有任何了解,请分享和解释。 PS: I also want to extract the time zone information. PS:我也想提取时区信息。
If you want a non-regex solution, you can use this : 如果您需要非正则表达式解决方案,则可以使用以下方法:
> new Date(Date.parse("2005-07-08T11:22:33+0000"))
Fri Jul 08 2005 13:22:33 GMT+0200 (CEST)
> new Date(Date.parse("2005-07-08T11:22:33+0000")).toUTCString()
"Fri, 08 Jul 2005 11:22:33 GMT"
And to get the timezone, you can use the getTimezoneOffset()
function 要获取时区,可以使用getTimezoneOffset()
函数
var my_date = new Date(Date.parse("2005-07-08T11:22:33+0000"));
var timezone_offset = my_date.getTimezoneOffset();
The time-zone offset is the difference, in minutes, between UTC and local time. 时区偏移量是UTC与本地时间之间的差(以分钟为单位)。 Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. 请注意,这意味着如果本地时区在UTC之后,则偏移量为正;如果在本地时区之前,则偏移量为负。 For example, if your time zone is UTC+10 (Australian Eastern Standard Time), -600 will be returned. 例如,如果您的时区是UTC + 10(澳大利亚东部标准时间),则将返回-600。 Daylight savings time prevents this value from being a constant even for a given locale 夏时制即使在给定的语言环境下也可以防止该值保持恒定
yes you can do using split method . 是的,您可以使用split方法。
<!DOCTYPE html> <html> <body> <p>Click the button to display the array values after the split.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var str = "2006-08-15T00:00:00+05:30"; var res = str.split("T"); console.log("date:" +res[0]); console.log("time:" +res[1]); } </script> </body> </html>
If you used Date()
function, Then you can create Date Object
to get all data without regular expression
that you want. 如果使用Date()
函数,则可以创建Date Object
以获取所有数据,而无需所需的regular expression
。
Example 例
var Obj = new Date();
var month = Obj.getMonth();
var date = Obj.getDate();
var year = Obj.getFullYear();
var hour = Obj.getUTCHours();
var minutes = Obj.getUTCMinutes();
Here is the all Date Object Methods 这是所有Date对象的方法
You could split the string an then you get an array, with the information: 您可以将字符串拆分,然后获得一个数组,其中包含以下信息:
date.split(/[-\+:T]/g);
// ["2006", "08", "15", "00", "00", "00", "05", "30"]
Also, you should check if the string contains a + or a - before using the timezone. 另外,在使用时区之前,您应该检查字符串是否包含+或-。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.