如何以y-m-d格式提取日期值?

时间:2016-07-02 13:16:54

标签: php regex string date-parsing

我们假设我有这个日期:void DirSearch(string rootDirectory, string filesExtension, string textToSearch, BackgroundWorker worker, DoWorkEventArgs e) { List<string> filePathList = new List<string>(); List<string> restrictedFiles = new List<string>(); int overallfiles = 0; int numberoffiles = 0; int numberofdirs = 0; try { filePathList = SearchAccessibleFilesNoDistinct(rootDirectory, null).ToList(); } catch (Exception err) { string ad = err.ToString(); } foreach (string file in filePathList) { try { _busy.WaitOne(); if (worker.CancellationPending == true) { e.Cancel = true; return; } List<MyProgress> prog = new List<MyProgress>(); int var = File.ReadAllText(file).Contains(textToSearch) ? 1 : 0; overallfiles++; if (var == 1) { numberoffiles++; prog.Add(new MyProgress { Report1 = file, Report2 = numberoffiles.ToString() }); backgroundWorker1.ReportProgress(0, prog); } numberofdirs++; label1.Invoke((MethodInvoker)delegate { label1.Text = numberofdirs.ToString(); label1.Visible = true; }); } catch (Exception) { restrictedFiles.Add(file); continue; } } } 。我想要实现的是:

2016-07-27

我尝试过:

  • $year = 2016; $month = 07; $day = 27;
    返回$year = preg_match("/^[^-]*/", "2016-07-27");
  • 1
    返回$month = preg_match("(?<=\-)(.*?)(?=\-)", "2016-07-27");
  • Warning: preg_match(): Unknown modifier '('

如何在破折号之间提取数字并将它们存储到下面的变量中?

2 个答案:

答案 0 :(得分:4)

不要重新发明轮子 - date_parse会为你做所有繁重的工作:

$parsed = date_parse('2016-07-27');
$year = $parsed['year'];
$month = $parsed['month'];
$day = $parsed['day'];

答案 1 :(得分:1)

如果它是一个不会改变其格式的字符串,那么你可以简单地这样做:

$date = '2016-07-27';
list($year, $month, $day) = explode('-', $date);

echo $year; // 2016
echo $month; // 07
echo $day; // 27

但是,如果日期格式发生变化,则应使用date_parse或其他DateTime方法。