2

Input time format:

2016-05-03 01:38:54

Ouput time format:

2016-05-03T01:38:54.003Z

Here what is .003, is it millisecond or microsecond?

And in PHP the microsecond format is 'u', but when I am trying to use this using the following code snippet, I am getting 6 digits after the decimal point:

<?php

date_default_timezone_set("Asia/Kolkata");

echo date('Y-m-d\TH:i:s.u\Z', strtotime("2016-05-03 01:38:54"));

I am getting the output as:

2016-05-03T01:38:54.000000Z

But in this output after the decimal point it is showing 6 digit, which I want to change it to 3 digit. How can I do that?

So how should I get the output format?

RJParikh
  • 4,096
  • 1
  • 19
  • 36
Debesh Nayak
  • 244
  • 4
  • 16
  • Z is Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. – Ravi Hirani Jun 03 '16 at 05:34
  • This link has all you need. http://php.net/manual/en/function.date.php – Ravi Hirani Jun 03 '16 at 05:34
  • PHP doesn't use micro-seconds, but if you need go for `microtime`. and this will do: `echo str_replace("+05:30", ".000Z", date('c', strtotime('2016-05-03 01:38:54')));` – Thamilhan Jun 03 '16 at 05:47

4 Answers4

3
 date_default_timezone_set("Asia/Kolkata");
    $t = strtotime('2016-05-03 01:38:54');
    $micro = sprintf("%06d",($t - floor($t)) * 1000000);
    $d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );

    $new= $d->Format("Y-m-d\T H:i:s.u\Z");
    echo substr($new, 0, -4) ."Z";

//output 2016-05-03T 01:38:54.030Z
anju
  • 589
  • 12
  • 25
0

I'd use the DateTime class as follows:

$tz = new DateTimeZone('Asia/Kolkata');
$date = new DateTime('2016-05-03 01:38:54', $tz );
echo substr($date->format('Y-m-d\TH:i:s.u'), 0, -3) ."Z";
// 2016-05-03T01:38:54.000Z

http://ideone.com/Wrrve9


According to PHP date manual

u Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
0

try this

$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );

print $d->format("Y-m-d\T H:i:s.u\Z"); // note at point on "u"
Abdul Hameed
  • 263
  • 4
  • 19
0

The cleanest solution might be a modified version of adityabhai at gmail dot com's comment on http://php.net/manual/en/function.date.php:

echo date('Y-m-d H:i:s' . substr((string)microtime(), 1, 4));
BudwiseЯ
  • 1,846
  • 2
  • 16
  • 28