UTC date not changing in IST date format in PHP - php

As based on REST API page documentation the date is in UTC format as yyyy-MM-dd’T’HH:mm:ss (Eg: 2017-01-02T08:12:53)
When I hit the API, I am getting the date as 1619693307000. Converted this date using strtotime() in PHP.
What is the correct way to convert this date in d-m-Y h:i:s IST in PHP.
I used this code to do the same.
<?php echo date("Y-m-d h:i:s", '1619693307000') ?> //OUTPUT: 53296-01-14 01:00:00
The above output is absolutely wrong.
Confusion is to correctly convert UTC to IST zone and what should i do to see the correct output as the date in PHP. I read all threads on this StackOverflow and Google.
but all not helpfull.
Please help...

Your timestamp has too many digits, so it's likely in milliseconds. This seems to be a common javascript thing. So divide by 1000, and I highly recommend using the DateTime objects/interfaces rather than the old-style strtotime()/date()/etc functions.
$millis = 1619693307000;
$seconds = $millis / 1000;
$t = new DateTime('', new DateTimezone('Asia/Kolkata'));
$t->setTimestamp($seconds);
var_dump(
$t->format("Y-m-d h:i:s T")
);
Output:
string(23) "2021-04-29 04:18:27 IST"
Also "UTC" is not a format, it's a timezone. 2017-01-02T08:12:53 is an ISO8601-format. It also has a handy format shortcut:
var_dump(
$t->format("c")
);
Output:
string(25) "2021-04-29T16:18:27+05:30"
Edit: Different timezone and format:
$t = new DateTime('', new DateTimezone('UTC'));
$t->setTimestamp($seconds);
var_dump(
$t->format("Y-m-d\Th:i:s")
);
Output:
string(19) "2021-04-29T10:48:27"

Related

strtotime() is returning a 1970 date and don't comparing well to time()

I'm trying to convert a string that enters in my program from a JSON to a date, so I can compare it to actual time.
I'm using strtotime() but it converts the original date to 01/01/1970 12:00:00.
Here's my code:
var_dump($requestOrder->date);
$requestDate= date('d/m/Y h:i:s', strtotime($requestOrder->date));
var_dump($requestDate);
Where, date inside the $requestOrder is equal to "24/12/2021 00:00:00".
And here's what I'm getting:
string(19) "24/12/2021 00:00:00"
string(19) "01/01/1970 12:00:00"
I need to convert it to a date because, lately, in some point of my code, I do this:
if($requestDate< date('d/m/Y h:i:s', time())) {
...
}
I've been trying a lot of options to solve this problem, such as changing the / to -, using other formats for the date, etc, but with no luck. In the case of using a str_replace to change the / to -, it works and doesn't show a 70's date, but then it doesn't do the comparison well, it always detects the date smallest to actual one.
Does someone see what I'm skipping?
The date() function returns a string not a DateTime object. It would be better to use the actual DateTime class and its createFromFormat function.
$requestDate = date_create_from_format('d/m/Y h:i:s', $requestOrder->date);
or object oriented style
$requestDate = DateTime::createFromFormat('d/m/Y h:i:s', $requestOrder->date);
https://www.php.net/manual/en/datetime.createfromformat.php
Please check below code:
$requestOrder->date="24/12/2021 00:00:00";
$date=str_replace("/",'-',$requestOrder->date);
if(strtotime($date)>time())
{
//this will execute as request date is greater than current date
}
if(strtotime($date)<time())
{
//this will not execute as current date less than request date
}

How to convert T-Z string to australian time? [duplicate]

So I've checked the list of supported time zones in PHP and I was wondering how could I include them in the date() function?
Thanks!
I don't want a default timezone, each user has their timezone stored in the database, I take that timezone of the user and use it. How? I know how to take it from the database, not how to use it, though.
For such task, you should really be using PHP's DateTime class. Please ignore all of the answers advising you to use date() or date_set_time_zone, it's simply bad and outdated.
I'll use pseudocode to demonstrate, so try to adjust the code to suit your needs.
Assuming that variable $tz contains string name of a valid time zone and variable $timestamp contains the timestamp you wish to format according to time zone, the code would look like this:
$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');
DateTime class is powerful, and to grasp all of its capabilities - you should devote some of your time reading about it at php.net. To answer your question fully - yes, you can adjust the time zone parameter dynamically (on each iteration while reading from db, you can create a new DateTimeZone() object).
If I understood correct,You need to set time zone first like:
date_default_timezone_set('UTC');
And than you can use date function:
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
The answer above caused me to jump through some hoops/gotchas, so just posting the cleaner code that worked for me:
$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('America/New_York'));
$dt->setTimestamp(123456789);
echo $dt->format('F j, Y # G:i');
Use the DateTime class instead, as it supports timezones. The DateTime equivalent of date() is DateTime::format.
An extremely helpful wrapper for DateTime is Carbon - definitely give it a look.
You'll want to store in the database as UTC and convert on the application level.
It should like this:
date_default_timezone_set('America/New_York');
U can just add, timezone difference to unix timestamp.
Example for Moscow (UTC+3)
echo date('d.m.Y H:i:s', time() + 3 * 60 * 60);
Try this. You can pass either unix timestamp, or datetime string
public static function convertToTimezone($timestamp, $fromTimezone, $toTimezone, $format='Y-m-d H:i:s')
{
$datetime = is_numeric($timestamp) ?
DateTime::createFromFormat ('U' , $timestamp, new DateTimeZone($fromTimezone)) :
new DateTime($timestamp, new DateTimeZone($fromTimezone));
$datetime->setTimezone(new DateTimeZone($toTimezone));
return $datetime->format($format);
}
this works perfectly in 2019:
date('Y-m-d H:i:s',strtotime($date. ' '.$timezone));
I have created this very straightforward function, and it works like a charm:
function ts2time($timestamp,$timezone){ /* input: 1518404518,America/Los_Angeles */
$date = new DateTime(date("d F Y H:i:s",$timestamp));
$date->setTimezone(new DateTimeZone($timezone));
$rt=$date->format('M d, Y h:i:s a'); /* output: Feb 11, 2018 7:01:58 pm */
return $rt;
}
I have tried the answers based on the DateTime class. While they are working, I found a much simpler solution that makes a DateTime object timezone aware at the time of creation.
$dt = new DateTime("now", new DateTimeZone('Asia/Jakarta'));
echo $dt->format("Y-m-d H:i:s");
This returns the current local time in Jakarta, Indonesia.
Not mentioned above. You could also crate a DateTime object by providing a timestamp as string in the constructor with a leading # sign.
$dt = new DateTime('#123456789');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('F j, Y - G:i');
See the documentation about compound formats:
https://www.php.net/manual/en/datetime.formats.compound.php
Based on other answers I built a one-liner, where I suppose you need current date time. It's easy to adjust if you need a different timestamp.
$dt = (new DateTime("now", new DateTimeZone('Europe/Rome')))->format('d-m-Y_His');
If you use Team EJ's answer, using T in the format string for DateTime will display a three-letter abbreviation, but you can get the long name of the timezone like this:
$date = new DateTime('2/3/2022 02:11:17');
$date->setTimezone(new DateTimeZone('America/Chicago'));
echo "\n" . $date->format('Y-m-d h:i:s T');
/* Displays 2022-02-03 02:11:17 CST "; */
$t = $date->getTimezone();
echo "\nTimezone: " . $t->getName();
/* Displays Timezone: America/Chicago */
$now = new DateTime();
$now->format('d-m-Y H:i:s T')
Will output:
29-12-2021 12:38:15 UTC
I had a weird problem on a hosting. The timezone was set correctly, when I checked it with the following code.
echo ini_get('date.timezone');
However, the time it returned was UTC.
The solution was using the following code since the timezone was set correctly in the PHP configuration.
date_default_timezone_set(ini_get('date.timezone'));
You can replace database value in date_default_timezone_set function,
date_default_timezone_set(SOME_PHP_VARIABLE);
but just needs to take care of exact values relevant to the timezones.

How to convert a Datetime string to standard mysql

I made a function in php to convert date and time coming from a txt to the mysql standard.
But she is turning the month wrong.
I have tried all these conversions but to no avail.
I would like your help because I don't know what else to do.
function convertstringdate('05/02/202116:43:49'){
$date = new DateTime($datetime);
return date_format($date, "Y-m-d H:i:s");
}
or
$input = '05/02/202116:43:49';
$date = strtotime($input);
echo date('Y-m-d H:i:s', $date);
Since you know the format of your datetime-string I suggest you use createFromFormat() like so:
$string = '05/02/202116:43:49';
$dateTime = DateTime::createFromFormat('d/m/YG:i:s', $string);
var_dump(date_format($dateTime, "Y-m-d H:i:s"));
// output: string(19) "2021-02-05 16:43:49"
Note that I am not sure if 05 or 02 is supposed to be the month in your example, so if this seems wrong to you you might just have to switch around d/m in the format string and make it m/d.
For explanation what character means what poriton of the datetime, see the linked above documentation reference.

PHP date limit 1970

I'm programming a site about genealogy, I used the date input to acquire dates, and
$datamm= strftime('%Y-%m-%d', strtotime($_POST['datamm']));
to convert the dates for the database, but the minimum value that I can get is 1970-01-01. I need to acquire dates between 1500 and current day.
What can I do to solve the problem?? I prefer procedural solution if it is possible.
Here is an example,
<?php
$date = new DateTime( '01-01-1950' );
echo $date->format( 'Y-m-d' );
?>
DateTime is great, you can do all sorts once you understand it.
For instance, this will add a year and echo the start and end dates,
<?php
$date = new DateTime( '01-01-1950' );
echo $date->format( 'Y-m-d' )."\n";
$date->modify( '+1 years' );
echo $date->format( 'Y-m-d' );
?>
If you know that in which format your date is coming from input then you can try:
$datamm = DateTime::createFromFormat('j-M-Y', $_POST['datamm']);//You know that date is coming in j-M-Y format
echo $date->format('Y-m-d'); // You can save in Y-m-d format in database
if you are taking timestamp as input then :
$date = date('Y-m-d',$_POST['datamm']);//you are taking timestamp like : 30000000000 as an input
echo $date;//make in database in Y-m-d format
I hope it helps
Try this, use createFromFormat
// pass your date format
$date = DateTime::createFromFormat('d M Y','17 Jan 1500');
echo $date->format('Y-m-d');
DEMO
You should probably focus on using some 3rd party library instead of official PHP's datetime functions.
For example, for your advanced date-time manipulating requirements, a good alternative for PHP's standard datetime would be moment.php
It's inspired by moment.js library whose goal is to fix common date-time programming issues, and bring standardization to higher level.
You can obtain it via composer like:
{
"require": {
"fightbulc/moment": "*"
}
}
Or via github for manual installation.
To parse various input date consult a manual, below is example:
$m = new \Moment\Moment('1503-04-25T03:00:00', 'CET');
There is also other alternatives to explore, for example:
https://github.com/swt83/php-date

How can I convert a epoch time stamp to a UTC format like 2014-06-25T14:38:52.359Z in PHP

I am looking to convert an EPOCH timestamp (like 1372190184) to a format 2014-06-25T14:38:52.359Z.
I have tried the following code, but the format I get is different from what I need.
$start = new DateTime(date('r', '1372190184'));
$startDateText = $start->format('Y-m-dTH:i:sZ');
var_dump($startDateText);
exit();
But I get the output as string(30) "2013-06-25GMT+020021:56:247200" which is different from what I expect.
You forgot the backslashes in your format, and the dollar sign before startDateText in the dump:
$start = new DateTime(date('r', '1372190184'));
$startDateText = $start->format('Y-m-d\TH:i:s\Z');
var_dump($startDateText);
Also, if you're looking for microseconds, add the u format character.
You should be setting the date_default_timezone_set to UTC for your desired output. Format as you wish. And make sure to escape special characters in the format.
date_default_timezone_set('UTC');
$epoch = 1340000000;
echo gmdate('r', $epoch);
You can convert to UTC format date from a date string, for example:
$date = '2022-05-02 11:50:00';
$date = date('Y-m-d\TH:i:s\Z', strtotime($date));
echo $date;

Categories