简体   繁体   中英

What is this date format called and how do I parse it?

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.

Try:

$oDate = DateTime::createFromFormat('Yz', 201026);
echo $oDate->format('Y-m-d');

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

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)

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

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));

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