简体   繁体   中英

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.

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

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. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, if your time zone is UTC+10 (Australian Eastern Standard Time), -600 will be returned. Daylight savings time prevents this value from being a constant even for a given locale

yes you can do using split method .

 <!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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM