0

I need to convert a date string in a format like bellow using PHP,

2015-07-30T08:05:00.917Z

I try to convert using the bellow code,

echo str_replace('+00:00', '.917Z', gmdate('c', strtotime('2016-04-05 00:00:00')));

This will create 2016-04-05T00:00:00.917Z This is not correct,Is there any function to create date like this format?

Shijin TR
  • 7,516
  • 10
  • 55
  • 122
  • 2
    `echo (new DateTime('2016-04-05 00:00:00'))->format('Y-m-d\TH:i:s.917\Z');` – Mark Baker Apr 06 '16 at 09:01
  • 1
    `.917` is the number of milliseconds the the date you posted. Your input date doesn't contain information about milliseconds, you should not add `.917` to it but either append `.000` or use a function that supports milliseconds ([`DateTime::format()`](http://php.net/manual/en/datetime.format.php)) – axiac Apr 06 '16 at 09:02

3 Answers3

2

There are two ways to create date from String.

1. date_create_from_format
   $date=date_create_from_format("DATE_FORMAT",$dateString);

2. $date=new DateTime();
   $date=$date->createFromFormat("DATE_FORMAT", $dateString);

Using following link to get your DATE_FORMAT.

http://php.net/manual/en/function.date.php

Alok Patel
  • 7,842
  • 5
  • 31
  • 47
0

You can do it as @Alok has mentioned in his answer. Or similarly using the following code.

$date = DateTime::createFromFormat('U.u', microtime(TRUE));

echo $date->format('Y-m-d\TH:i:s.u\Z');

Note that the microsecond mentioned in your question is of 3 digits. But generally php date formatting outputs microseconds in 6 digits precision.

Like the above code outputs 2016-04-06T09:24:50.830000Z

So I think you have to do some hack there if the digit precision is important.

Himel Nag Rana
  • 744
  • 1
  • 11
  • 19
0

Pass it through the function formatTime. This creates a new DateTime object in PHP called $date that can also easily be manipulated if you need. The examples below formats the date in two different ways, both work.

Procedural Style:

function formatTime($millis) { 
        $date = new DateTime($millis); 
        return date_format($date, 'l, jS F Y \a\t g:ia'); 
}

Object Oriented Style:

function formatTime($millis) { 
        $date = new DateTime($millis); 
        return $date->format('l, jS F Y \a\t g:ia'); 
}

The format for date can be found at this link: http://php.net/manual/en/function.date.php

Hope this helps.