简体   繁体   English

这个日期格式叫什么,我该如何解析它?

[英]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. 例如,第一个日期是1954年的第203天,即1954年7月22日。

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. PHP。

Try: 尝试:

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

For Java, see SimpleDateFormat . 对于Java,请参阅SimpleDateFormat You want yyyyDDD as the format (year, then day in year). 你想要yyyyDDD作为格式(年份,然后是一年中的一天)。

Assuming you get it as a string in C#... 假设你在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) (注意日期编号的-1偏移量,因为您已经在第1天开始)

In PHP to format the date: 用PHP格式化日期:

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 它返回一个DateTime对象

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM