Sonu Mishra
Sonu Mishra

Reputation: 1779

Regular expression to parse the time-stamp string in ActionScript3

I am working on a project in ActionScript3. I have this function that parses a time-stamp string.

private function convertTimestampToNumber(timestamp:String):Number {
    //YYYY-MM-DD HH:mm:SS:sss
    var re:RegExp = /(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})\s(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})\.(?P<msec>\d{3})/;
    var result:Array = re.exec(timestamp);
    Alert.show(timestamp, "Timestamp string", Alert.OK);

    return (10000000000000 * parseInt(result.year)
        + 100000000000 * parseInt(result.month)
        + 1000000000 * parseInt(result.day)
        + 10000000 * parseInt(result.hour)
        + 100000 * parseInt(result.min)
        + 1000 * parseInt(result.sec)
        + parseInt(result.msec));
}

This seems to work fine for all time-stamps except "2016-08-01 09:19:43.23". Here it throws an error:

[Fault] exception, information=TypeError: Error #1009: Cannot access a property or method of a null object reference.

I thought since the millisecond part of this time-stamp is only 2 chars long, it was throwing error. To fix this I changed the millisecond part of the regular expression to (?P<msec>\d{2|3}) thinking that now it would consider both 2-character and 3-character long millisecond as valid, but now it throws the same error on "2015-11-19 15:28:29.737".

What will be the correct regular expression that can consider both scenarios as valid?

Upvotes: 1

Views: 483

Answers (2)

tatactic
tatactic

Reputation: 1385

I'm not sure to understand your question, but if you use de Date Class, you may format your result as you want.

Check and adapt the DateTimeFormatter code here bellow And check for setDateTimePattern() method too.:

import flash.utils.getTimer;
import flash.globalization.DateTimeFormatter;
import flash.globalization.DateTimeStyle;

var currentTime = new Date();
function formatDate(date:Date) {
    var dtf:DateTimeFormatter = new DateTimeFormatter("fr-FR");
    // or new DateTimeFormatter("en-EN");
    dtf.setDateTimePattern("yyyy-MM-dd hh:mm:ss");
    var longDate:String = dtf.format(date);
    trace(longDate)+getTimer();
    //trace("   *** LocaleID requested=" + dtf.requestedLocaleIDName);
    //trace("   *** Format requested (" + dtf.getDateTimePattern() + ")");
}
trace(" setDateTimePattern example");
formatDate(currentTime);
// output the current time formated as "yyyy-MM-dd hh:mm:ss"
// no Milliseconds avalaible now!

Just check the reference, and you'll find an answer AMO. Hope this helps.

Upvotes: 0

Sebastian Lenartowicz
Sebastian Lenartowicz

Reputation: 4874

Your change is almost right. What you can do is this:

(?P<msec>\d{1,3})

Which will match any number of milliseconds, from 1 digit (possible, though unlikely to appear) to 3.

Upvotes: 2

Related Questions