在php中将字符串转换为日期

问题描述 投票:-1回答:4

我有一个包含日期和时间的字符串。我的字符串的格式是yyyymmddtime。例如。 20171125123000209。这是我的完整字符串,其中首先是月份,然后是月份,然后是该时间之后的第二天。如何通过转换为可读日期格式从中检索日期。我尝试使用php的日期功能。但产量不如预期。请帮忙。

php date
4个回答
2
投票

试试这个

<?php
  $str_date= "20171125123000209";
  $exiting_date_format='Ymd';
  //first 8 characters from given date string in second parameter below
  $date = DateTime::createFromFormat($exiting_date_format, substr($str_date,0,8));
  echo $date->format('Y-m-d');//specify desired date format
?>

输出:

2017-11-25

DateTime::createFromFormat - 根据指定的格式解析时间字符串


0
投票

你可以使用php的date()函数

<?php
  $full_date= "20171125123000209";
  echo date('dS F h:i:s A', $full_date);
  //Output = 31st May 12:30:09 AM
?>

要么,

要像现在一样从时间戳中获取日期,

 $timestamp= time(); //Or your timestamp here
 $date = date('d-m-Y', $timestamp); //Inside first parameter, give your date format
 echo $date; //17-12-2017

要么,

要从字符串中获取任何内容,您还可以使用php的substr()函数。

<?php
  $full_date= "20171125123000209";
  $year = substr($full_date, 0, 4);
  $month = substr($full_date, 4, 2);
  $date = substr($full_date, 6, 2);

  echo 'Year = '.$year.' ';
  echo 'Month = '.$month.' ';
  echo 'Date = '. $date.' ';
?>

输出:年= 2017月= 11日= 25

Test in jdoodle

About substr() function in php


0
投票

根本没有必要操纵字符串。 PHP的DateTime类支持使用u格式修饰符本地解析包含毫秒的字符串:

$str = '20171125123000209';
$date = DateTime::createFromFormat('YmdHisu', $str);

使用新的$date对象,您可以转换为您正在寻找的任何格式,例如

echo $date->format("F j Y, g:i a");
// November 25 2017, 12:30 pm

https://eval.in/920636


-1
投票
$your_strtotime_val = ""; //20171125123000209
$convert_to_date = date("m-d-Y h:i:s",$your_strtotime); // [m-d-Y h:i:s] this depending on how you convert date in first time so be careful
© www.soinside.com 2019 - 2024. All rights reserved.