user3353762
user3353762

Reputation: 103

How to convert a PHP DateTime object to ISO string?

I have a date that I receive in MS format for JSON dates. It looks like this:

/Date(1365004652303)/

I can convert it to a PHP DateTime object by doing this:

$timestamp = round(((int) $originalMSdate) / 1000);
$convertedDate = new DateTime();
$convertedDate->setTimestamp($timestamp);

Ultimately, though, I need it to be a string in ISO 8601 format. I tried then converting it to an ISO date object & then converting that to a string with strval() but strval() doesn't work on date objects.

I've also tried

$dateString = date_format($convertedDate, 'YY-MM-DD H:i:s'); 

but I need it to also include timezone info, like this: 2015-10-01T21:22:57.057Z I don't see characters for that in date_format.

How can I achieve this?

EDIT: I should clarify that I'm not printing the resulting string. I need to pass it to a field in a database that accepts a string datatype.

Upvotes: 2

Views: 3306

Answers (3)

Nashir
Nashir

Reputation: 284

this one is worked for me. For more please refer this article.

$date = date('Y-m-d H:m:s');

echo date('c', strtotime($date));                // 2020-04-08T16:04:56+05:30
echo date(DateTime::ISO8601, strtotime($date));  // 2020-04-08T16:04:56+0530
echo date(DateTime::ATOM, strtotime($date));     // 2020-04-08T16:04:56+05:30

Upvotes: 0

user3353762
user3353762

Reputation: 103

This worked:

$timestamp = round(((int) $originalMSdate) / 1000);
$dateString = date('c', $timestamp);

The format isn't EXACTLY the same. It's in this format:

2016-04-25T14:27:00-05:00 rather than 2016-04-25T14:27:00.057Z

but it's close enough that I can do some manipulation to get what I need.

Upvotes: 0

Vijayanand Premnath
Vijayanand Premnath

Reputation: 3615

Please try the below code

<?php
// input
$time = microtime(true);
// Determining the microsecond fraction
$microSeconds = sprintf("%06d", ($time - floor($time)) * 1000000);
// Creating DT object
$tz = new DateTimeZone("Etc/UTC");
$dt = new DateTime(date('Y-m-d H:i:s.'. $microSeconds, $time), $tz);
$iso8601Date = sprintf(
    "%s%03d%s",
    $dt->format("Y-m-d\TH:i:s."),
    floor($dt->format("u")/1000),
    $dt->format("O")
);
// Formatting according to ISO 8601-extended
var_dump(
     $iso8601Date
);

Upvotes: 1

Related Questions