473,840 Members | 1,455 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting ISO8601 format to Date

Before I reinvent the wheel I thought I'd ask: anybody got a code snippet
that will convert the common ISO8601 date formats to a JS date?

By "common" I mean at the least ones described in this W3C note:

http://www.w3.org/TR/NOTE-datetime

For my requirements the code would be need to be open sourceable under the
BSD license.

If not then my plan is to do a RegEx for each of the formats and attempt to
match from the most complex to the least. (I'm not searching through
arbitrary text but rather examining a single value that SHOULD be a date in
one of those formats) Sound like a plan?

Jim Davis
Aug 29 '05 #1
6 4843
JRS: In article <de*********@ne ws1.newsguy.com >, dated Mon, 29 Aug 2005
14:05:21, seen in news:comp.lang. javascript, Jim Davis
<ne********@vbo ston.com> posted :
Before I reinvent the wheel I thought I'd ask: anybody got a code snippet
that will convert the common ISO8601 date formats to a JS date?

By "common" I mean at the least ones described in this W3C note:

http://www.w3.org/TR/NOTE-datetime
URLs should be encased in <...> or <URL:...> for optimum reader
satisfaction. However, you should remember that those who read News
off-line would prefer to see the information in the article itself.
For my requirements the code would be need to be open sourceable under the
BSD license.
Bovine Spongiform Disencephaly?
If not then my plan is to do a RegEx for each of the formats and attempt to
match from the most complex to the least. (I'm not searching through
arbitrary text but rather examining a single value that SHOULD be a date in
one of those formats) Sound like a plan?


The structure of the formats is, as I recall, rigid yyyy-mm-dd or yyyy-
Www-d or yyyy-ddd except that parts may be omitted. In that case, you
may only need the RegExps, as long as you are prepared to accept empty
parts. But note that ISO 8601:2000 allows some representations to be
used only by agreement.

Processing data in various ways until some form which might be correct
is tried is a very American thing to do, and usually leads to error in
the end. In a non-ISO context, success with Christmas Day does not
justify presumption of success with Guy Fawkes' Day.

Please read the newsgroup FAQ before asking questions. See below.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Aug 30 '05 #2
"Dr John Stockton" <jr*@merlyn.dem on.co.uk> wrote in message
news:bw******** ******@merlyn.d emon.co.uk...
JRS: In article <de*********@ne ws1.newsguy.com >, dated Mon, 29 Aug 2005
14:05:21, seen in news:comp.lang. javascript, Jim Davis
<ne********@vbo ston.com> posted :
Before I reinvent the wheel I thought I'd ask: anybody got a code snippet
that will convert the common ISO8601 date formats to a JS date?

By "common" I mean at the least ones described in this W3C note:

http://www.w3.org/TR/NOTE-datetime
URLs should be encased in <...> or <URL:...> for optimum reader
satisfaction. However, you should remember that those who read News
off-line would prefer to see the information in the article itself.


Point well taken.
For my requirements the code would be need to be open sourceable under the
BSD license.


Bovine Spongiform Disencephaly?


Well... in this case let's say that if you don't know then it doesn't matter
to you.
If not then my plan is to do a RegEx for each of the formats and attempt
to
match from the most complex to the least. (I'm not searching through
arbitrary text but rather examining a single value that SHOULD be a date
in
one of those formats) Sound like a plan?


The structure of the formats is, as I recall, rigid yyyy-mm-dd or yyyy-
Www-d or yyyy-ddd except that parts may be omitted. In that case, you
may only need the RegExps, as long as you are prepared to accept empty
parts. But note that ISO 8601:2000 allows some representations to be
used only by agreement.


I was able to address the problem with a coupla of RegExp's in the end. I
was hoping to be able to adopt something off the shelf, but finding nothing
went ahead and did it. Once it's been cleaned up I plan to release it to
community.

The purpose is not to represent a full 8601 parser (I'll leave that to much
bigger brains) - only to parse those (6) formats specified by the WC3 note.
Processing data in various ways until some form which might be correct
is tried is a very American thing to do, and usually leads to error in
the end. In a non-ISO context, success with Christmas Day does not
justify presumption of success with Guy Fawkes' Day.
I really haven't the faintest idea what you're talking about here... ;^)

This is not a "fishing expedition" but rather a situation where arbitrary
dates may be sent. The six formats required cover a range of progressive
specificity and so the parser should understand them all.
Please read the newsgroup FAQ before asking questions. See below.


The FAQ doesn't seem to inform this question... is there something specific
in it you're suggesting I missed? Or do you just say this a lot? ;^)

Jim Davis
Aug 31 '05 #3

Well... I think I've worked this out. I've appended the code below but if
anybody wants a copy let me know.

This handles (barring bugs!) the following subset of ISO datetime stamps:

YYYY (eg 1997)
YYYY-MM (eg 1997-07)
YYYY-MM-DD (eg 1997-07-16)
YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20Z)
YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01: 00)
YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30Z)
YYYY-MM-DDThh:mm:ss.sTZ D (eg 1997-07-16T19:20:30.45+ 01:00)
YYYY-MM-DDThh:mm:ss.sTZ D (eg 1997-07-16T19:20:30.45Z )

The code works well so far... but there are some caveats:

+) The RegExs at play here don't do much validation. For example while they
won't match a month of "14" they will match a month of "2" and a date of
"31". This will also only honors years from 1600 on (I've no desire to play
with Gregorian vrs Julian dates).

I've split out the expression fragments and maybe someday will add the
look-aheads required to do day of month validation... but I doubt I'll ever
bother with leap year validation. The rule here is "good enough for what I
need not perfect".

+) I've been leniant (and a little lazy) on the element separators. While
they are required you can use slashes, dashes, dots or colons. For
milliseconds you can use a dot or a comma. The ISO8601 standard is dashes
to separate date parts, colons to separate time parts and a dot (decimal) to
separate milliseconds.

+) If the input does not validate to a date a null is returned.

+) If there is no timezone information the date returned will be in local
time.

+) If the UTC indicator exists (a trailing "Z") then the date returned will
be in UTC time.

+) If timezone offset information exists it will be used to convert the
input to the local time.

If anybody finds any errors in this I'd much appreciate hearing about them!

Jim Davis
// Convert Dates from iso8601
function ISO8601ToDate(C urDate) {

// Set the fragment expressions
var S = "[\\-/:.]";
var Yr = "((?:1[6-9]|[2-9][0-9])[0-9]{2})";
var Mo = S + "((?:1[012])|(?:0[1-9])|[1-9])";
var Dy = S + "((?:3[01])|(?:[12][0-9])|(?:0[1-9])|[1-9])";
var Hr = "(2[0-4]|[01]?[0-9])";
var Mn = S + "([0-5]?[0-9])";
var Sd = "(?:" + S + "([0-5]?[0-9])(?:[.,]([0-9]+))?)?";
var TZ = "(?:(Z)|(?: ([\+\-])(1[012]|[0]?[0-9])(?::?([0-5]?[0-9]))?))?";

// RegEx the input
// First check: Just date parts (month and day are optional)
// Second check: Full date plus time (seconds, milliseconds and TimeZone
info are optional)
var TF;
if ( TF = new RegExp("^" + Yr + "(?:" + Mo + "(?:" + Dy + ")?)?" +
"$").exec(CurDa te) ) {} else if ( TF = new RegExp("^" + Yr + Mo + Dy + "T" +
Hr + Mn + Sd + TZ + "$").exec(CurDa te) ) {};

// If the date couldn't be parsed, return null
if ( !TF ) {
return null;
};

// Default the Time Fragments if they're not present
if ( !TF[2] ) { TF[2] = 1 } else { TF[2] = TF[2] - 1 };
if ( !TF[3] ) { TF[3] = 1 };
if ( !TF[4] ) { TF[4] = 0 };
if ( !TF[5] ) { TF[5] = 0 };
if ( !TF[6] ) { TF[6] = 0 };
if ( !TF[7] ) { TF[7] = 0 };
if ( !TF[8] ) { TF[8] = null };
if ( TF[9] != "-" && TF[9] != "+" ) { TF[9] = null };
if ( !TF[10] ) { TF[10] = 0 } else { TF[10] = TF[9] + TF[10] };
if ( !TF[11] ) { TF[11] = 0 } else { TF[11] = TF[9] + TF[11] };

// If there's no timezone info the data is local time
if ( !TF[8] && !TF[9] ) {
return new Date(TF[1], TF[2], TF[3], TF[4], TF[5], TF[6], TF[7]);
};
// If the UTC indicator is set the date is UTC
if ( TF[8] == "Z" ) {
return new Date(Date.UTC(T F[1], TF[2], TF[3], TF[4], TF[5], TF[6],
TF[7]));
};
// If the date has a timezone offset
if ( TF[9] == "-" || TF[9] == "+" ) {
// Get current Timezone information
var CurTZ = new Date().getTimez oneOffset();
var CurTZh = TF[10] - ((CurTZ >= 0 ? "-" : "+") +
Math.floor(Math .abs(CurTZ) / 60))
var CurTZm = TF[11] - ((CurTZ >= 0 ? "-" : "+") + (Math.abs(CurTZ ) % 60))
// Return the date
return new Date(TF[1], TF[2], TF[3], TF[4] - CurTZh, TF[5] - CurTZm,
TF[6], TF[7]);
};

};
Aug 31 '05 #4
JRS: In article <df*********@ne ws3.newsguy.com >, dated Tue, 30 Aug 2005
21:57:26, seen in news:comp.lang. javascript, Jim Davis
<ne********@vbo ston.com> posted :
I was able to address the problem with a coupla of RegExp's in the end.
Please do not use slang. A substantial portion of this newsgroup are
not native users of English or American, and may have only learned the
proper forms of English.
The purpose is not to represent a full 8601 parser (I'll leave that to much
bigger brains) - only to parse those (6) formats specified by the WC3 note.
Processing data in various ways until some form which might be correct
is tried is a very American thing to do, and usually leads to error in
the end. In a non-ISO context, success with Christmas Day does not
justify presumption of success with Guy Fawkes' Day.
I really haven't the faintest idea what you're talking about here... ;^)


Indeed - perhaps you are not well-informed about the history of pre-
colonial times.

This is not a "fishing expedition" but rather a situation where arbitrary
dates may be sent. The six formats required cover a range of progressive
specificity and so the parser should understand them all.


You still have not given those formats here.

Please read the newsgroup FAQ before asking questions. See below.


The FAQ doesn't seem to inform this question... is there something specific
in it you're suggesting I missed? Or do you just say this a lot? ;^)

Well, you could try searching it for 'date' 'dates' 'time' or 'times'.
After all, it was you, I think, who did not want to re-invent the wheel.
You could also think more deeply about "See below".

Validating the values of the digits of a date by RegExp is a waste of
effort, since it can be done so much more easily by other means (and, as
has been shown by posters here in the past, it can be done rapidly by
deploying concentrated cunning). Time field value validation by RegExp
in not unreasonable, but not necessary either.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Aug 31 '05 #5
"Dr John Stockton" <jr*@merlyn.dem on.co.uk> wrote in message
news:1Y******** ******@merlyn.d emon.co.uk...
JRS: In article <df*********@ne ws3.newsguy.com >, dated Tue, 30 Aug 2005
21:57:26, seen in news:comp.lang. javascript, Jim Davis
<ne********@vbo ston.com> posted :
I was able to address the problem with a coupla of RegExp's in the end.


Please do not use slang. A substantial portion of this newsgroup are
not native users of English or American, and may have only learned the
proper forms of English.


There's nothing here that actually makes one want to continue a conversation
with you.

I mean I can respect an asshole that knows he's an asshole and yet still
helps out... but you just truly like being an asshole, don't you?

Jim Davis
Sep 1 '05 #6
Jim Davis said the following on 8/31/2005 9:01 PM:
"Dr John Stockton" <jr*@merlyn.dem on.co.uk> wrote in message
news:1Y******** ******@merlyn.d emon.co.uk...
JRS: In article <df*********@ne ws3.newsguy.com >, dated Tue, 30 Aug 2005
21:57:26, seen in news:comp.lang. javascript, Jim Davis
<ne********@v boston.com> posted :

I was able to address the problem with a coupla of RegExp's in the end.


Please do not use slang. A substantial portion of this newsgroup are
not native users of English or American, and may have only learned the
proper forms of English.

There's nothing here that actually makes one want to continue a conversation
with you.

I mean I can respect an asshole that knows he's an asshole and yet still
helps out... but you just truly like being an asshole, don't you?


I see you have finally discovered what John Stockton is all about.....

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Sep 1 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
3690
by: Rick | last post by:
I need to store a date prior to the unix epoch, any pointers? -- Rick Digital Printing www.intelligence-direct.com
0
1459
by: Paul Bowman | last post by:
HI All I have a date 20020101T000000, 00+00 which is, apparently in the ISO8601 format. I need to get this date into a DateTime instance. This format is different to the style given in the MS literature. So it is not recoqnised by the Parse method. So I guess I need to use a custom formatter to convert it to what I
2
3764
by: Samuel | last post by:
Hello, I am trying to convert a local time into UTC ISO8601, then parse it back into local time. I tried the following: ---------------------- #!/usr/bin/python import time import datetime import xml.utils.iso8601
0
1252
by: rlaemmler | last post by:
Hi, I just migrated my web app to .NET 2.0. Part of the app creates some business objects from a MySQL query which is returned by a web service. Some of those objects contain DateTime properties. Using .NET 1.1 soap serialized a DateTime always in the ISO8601 format. e.g. "2006-01-27T07:42:11.3014976-08:00". Now using .NET 2.0 suddenly the DateTime objects instanciated from a MySQL query get serialized as "2006-01-26T18:40:56". Only...
11
6722
by: Rubic | last post by:
I was a little surprised to recently discover that datetime has no method to input a string value. PEP 321 appears does not convey much information, but a timbot post from a couple years ago clarifies things: http://tinyurl.com/epjqc > You can stop looking: datetime doesn't > support any kind of conversion from string.
2
7014
by: savigliano | last post by:
hello, i am doing a date comparation and i have reallize that the data i have in my database (general date format) it is causing me problems, and because i don´t need the time data i would like to convert all the general date data into short date format, so i would like to delete the time part of the data, it is any way i can do that ???? Thank you in advance and sorry for my english carlos
2
11192
by: Brian Parker | last post by:
I am beginning to work with VB2005.NET and I'm getting some problems with string formatting converting an application from VB6. VB6 code:- sTradeDate = Format(pArray(4,i Record), "mmddyy") pArray is a variant array containing a date string at pArray(4, iRecord) in the format "yyyy/mm/dd"
3
7164
by: Jef Driesen | last post by:
How can I convert a date string to a number (e.g. a time_t value or a tm struct)? I know about the strptime function, but then I have to know the format string. And that is a problem. I'm trying to autoformat the contents of text entries in a GUI. For numbers, I'm converting the text representation to the appropriate type (using atoi, atof, ...) and converting the result back to text with the correct format (using sprintf). But this does...
5
2074
by: =?Utf-8?B?emlubw==?= | last post by:
I need to convert a string as: "DEC 18 2007 2:49:40:783PM" to a date. This value is sent by SQL server as :select convert(varchar(30), creationDate, 109) from ... ... . I tried : Dim dt As DateTime Dim myCultureInfo As New CultureInfo("en-US") If DateTime.TryParseExact("Dec 18 2007 2:49:40:783PM", "mon dd yyyy hh:mi:ss:mmmAM", myCultureInfo, Globalization.DateTimeStyles.None, dt) Then .... ...
0
9856
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10916
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10657
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9436
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7836
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7022
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5872
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4071
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3136
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.