views:

2368

answers:

4

Is there any way to parse a string in the format HH:MM into a Date (or other) object using the standard libraries?

I know that I can parse something like "9/17/2008 10:30" into a Date object using

var date:Date = new Date(Date.parse("9/17/2008 10:30");

But I want to parse just 10:30 by itself. The following code will not work.

var date:Date = new Date(Date.parse("10:30");

I know I can use a custom RegEx to do this fairly easily, but it seems like this should be possible using the existing Flex API.

+1  A: 

Have you considered prepending "01/01/2000 " to the time string and then applying Date?

Alternately there's probably a tokenizer that will take the input and split it up at the : giving you an array of strings you can convert to integers. A tokenizer isn't hard to write, either, and can be fun if one doesn't exist in flex.

Adam Davis
+2  A: 

If you have to use the exact format you specified, then you need to parse it yourself.

Here is a simple example (not tested):

var str:String = "9/17/2008 10:30"

var items:Array = str.split(" ");
var dateElements:Array = items[0].split("/");
var timeElements:Array = items[1].split(":");

var n:Date = new Date(dateElements[2],
      dateElements[0],
      dateElements[1].
      timeElements[0],
      timeElements[1]);

If the time is not expressed in 24 clock, then there is no way to check for AM or PM (code will assume AM).

mikechambers
This code is not necessary. The original example I gave (pasted below) works just fine.var date:Date = new Date(Date.parse("9/17/2008 10:30");
Mike Deck
A: 

To answer your specific question: no, there's no library function to do what you want to do, but then there's no library function for parsing dates on the ISO format, on the German format, on the Swedish format, dates where the years are in roman numerals etc.

Why not use regular expressions? That's what they are for.

Theo
You make him seem silly for asking the question... Which is undue.Most languages at least have some library for parsing dates and times, so thinking that Flex supports such functionality is quite reasonable.
David Wolever
+2  A: 

As a simple and free solution, you could use some static methods of the DateField:

  • DateField.stringToDate(valueString:String, inputFormat:String):Date
  • DateField.dateToString(value:Date, outputFattern:String):String

But unfortunately they don't support hours/minutes/seconds (just the date).

In your specific case: the Date object always contains also a "date" information.. if it isn't important, couldn't you simply concatenate a standard date string before parsing?

Cosma Colanicchia