tags:

views:

101

answers:

5

I have a weird date format in some files I'm parsing. Here are some examples:

1954203
2012320
2010270

The first four digits are the year and the next three digits are day of year. For example, the first date is the 203rd day of 1954, or 7/22/1954.

My questions are:

  1. What's this date format called?
  2. Is there a pre-canned way to parse it? I don't want to reinvent the wheel here.

Edit: Sorry, I forgot to mention my language. PHP.

A: 

For Java, see SimpleDateFormat. You want yyyyDDD as the format (year, then day in year).

Ross Judson
A: 

Assuming you get it as a string in C#...

DateTime GetDate(string input)
{
    int year = Int32.Parse(input.Substring(0,4));
    int day = Int32.Parse(input.Substring(4,3));
    return (new DateTime(year,1,1)).AddDays(day - 1);
}

(Note the -1 offset for the day number, since you are already starting at day 1)

ZombieSheep
A: 

In PHP to format the date:

echo date_parse_from_format("Yz", $date);

You can also use

DateTime::createFromFormat("YZ", $date);

or it's alias

date_create_from_format("Yz", $date)

which returns a DateTime object

gcores
You would think that would work but it doesn't. It returns January 204th, 1954 and tells me the date is invalid.
Jason Swett
@Jason can you show the full code you're using?
Pekka
`print_r(date_parse_from_format("Yz", '1954203'));`
Jason Swett
@Jason but that is expected behaviour: You are dumping the `DateTime` object. You need to format the date to get it in the form you desire. Try `echo date_format(date_parse_from_format("Yz", '1954203'), "d-m-Y");`
Pekka
That gives an error. I don't care to go any further down this path, though, since one of the other answers has solved my problem.
Jason Swett
+2  A: 

Try:

$oDate = DateTime::createFromFormat('Yz', 201026);
echo $oDate->format('Y-m-d');
Simon
Doesn't work because `date_parse_from_format()` doesn't work as expected.
Jason Swett
@Jason it works fine for me on PHP 5.3 on Windows
Pekka
@Pekka: Of course, `date_parse_from_format` doesn't exist prior to 5.3.0...
R. Bemrose
@R.Bemrose yes, true. But that doesn't seem to be the OP's problem, he claims that it returns a broken result
Pekka
The answer has been changed since I originally commented on it. This works just fine. However, you have to subtract 1 from the day in order for the result to be accurate (try a date of 2010001 to see what I mean).
Jason Swett
A: 

Turns out what I wanted was this:

$date = '1954203';
$year = substr($date, 0, 4);
$day = substr($date, 4, 3);
$new_date = date("Y-m-d", mktime(1, 1, 1, 1, $day, $year));
Jason Swett
Awww, I'm not sure whether this is not a good idea, as it will have to work with negative timestamps. (Unix time starts January 1st, 1970). If you can, use one of the `DateTime` suggestions
Pekka
Good point. I wish I had a better solution. However, this works for dates on or after January 1st, 1902, which suits my purpose well enough.
Jason Swett