I am using the following code to generate time stamps I always get different results for the same input on
$EventDateZone = new DateTime(str_replace('/', '-', $record['Date']), new DateTimeZone(Config::get('app.timezone')));
$EventDate = strtotime($EventDateZone->format("Y-m-d"));
$EventTimeZone = new DateTime($record['Time'], new DateTimeZone(Config::get('app.timezone')));
$EventTime = strtotime($EventTimeZone->format("H:i:s"));
The variables $record['Date] includes 01/04/2014 and $record['Time'] includes 09:26:00 AM and Config::get('app.timezone') is Asia/Dubai
The problem with the converted time it is always different here are the result for the converted time 1398576360 and 1398662760
I need the generated time stamp to be identical as this record will be stored in the database and I don't want to have it duplicated.
The date value does not contain a time, and the time value does not contain a date. UNIX timestamps however are compound values which are date-time values and must contain both. When you instantiate a new DateTime object and you give it an incomplete timestamp (i.e. missing either date or time), it fills in the missing values from the current time. And that will of course always be different.
You'll have to instantiate the DateTime object with both to get your UNIX timestamp. You cannot output a UNIX timestamp separately for date and time, because that doesn't make any sense. Your strtotime code doesn't make any sense. You can separate the DateTime object into date and time components again later if necessary, but not into two separate UNIX timestamps.
$event = DateTime::createFromFormat(
'd/m/Y H:i:s',
"$record[Date] $record[Time]",
new DateTimeZone(Config::get('app.timezone'))
);
echo $event->getTimestamp();
echo $event->format('Y-m-d');
echo $event->format('H:i:s');
Related
I have a Laravel-based app that is used by people from various parts of the US.
I am capturing a timestamp in Javascript when the user takes a specific action, and then I am submitting that timestamp as form data, for the Laravel/PHP to process.
The timestamp that I am capture in Javascript is in typical "YYYY-MM-DD HH:MM:SS" format.
I have the timezone the user is in stored in a database.
I basically want to take that timestamp, and convert it to UTC time, so that all timestamps in the database are UTC.
That is where I am struggling.
I have the following PHP code:
$defaultTime = request('submitted-time-stamp'); //In this case, we'll say 2022-12-21 12:01:01
$defaultTZ = $user->time_zone; //Translates to America/Denver
$utcTime = new DateTime($defaultTime);
$convertedTime = $utcTime1->setTimeZone(new DateTimeZone('UTC'));
$formattedTime = $convertedTime->format("Y-m-d H:i:s");
echo $formattedTime;
This code – it isn't producing any errors per sé... but it is showing the wrong time. It's showing the time that it went in as, not the time converted to UTC.
Basically, if I submit "2022-12-21 12:01:01" as the time, the converted time SHOULD be "2022-12-21 19:01:01", but it's still just echoing out "2022-12-21 12:01:01".
What am I missing here?
setTimezone() changes the timezone of the object from whatever default it was created with. I.e., it means, "convert from the existing timezone to this new timezone." It does not mean, "interpret the time as if it were in this timezone." If the original string didn't contain some sort of timezone identifier, then that default is whatever your PHP config says.
$when = new DateTime('2022-12-21 12:01:01');
echo $when->getTimeZone()->getName();
This will be the same as:
echo date_default_timezone_get();
Which is probably not what you want unless all your users are in the same timezone as your server.
In order to create a DateTime object in a specific known timezone that is not the same as your server's default, you'll need one of two things -- either a timezone representation in the input string:
$when = new DateTime('2022-12-21 12:01:01 America/New_York');
Or an explicit default timezone passed as a second parameter to the DateTime constructor:
$userDefaultTzStr = 'America/New_York'; // read this value from the database
$defaultTz = new DateTimeZone($userDefaultTzStr);
$when = new DateTime('2022-12-21 12:01:01', $defaultTz);
This latter method is (probably) preferred. If the input string contains any sort of timezone identifier, that will be used and the second parameter will be ignored. But if the input string does not contain any sort of timezone identifier, then the string will be interpreted as if it were in the indicated timezone.
Using Carbon it's very trivial.
use Carbon\Carbon;
$date = Carbon::create(request('submitted-time-stamp'), $user->time_zone);
$date->tz('UTC');
echo $date->format('Y-m-d H:i:s');
It should be the same thing with Laravel's Date facade.
use Illuminate\Support\Facades\Date;
$date = Date::create(request('submitted-time-stamp'), $user->time_zone);
$date->tz('UTC');
echo $date->format('Y-m-d H:i:s');
I have a website which saves images into a database. I have successfully made a function that calculates the date that an image is added and this value is also saved into the database. I now want to calculate the date two weeks ahead from the addition date. This will show the date that the image file will cease to exist in the database.
I used the function:
$dateofaddedimage= date("d/m/Y");
This calculate thee current date of the addition of the image.
I am aware that there is the strtodate() function, but i don't think it will help.
Does anyone know how to add two weeks onto this function?
Thanks!
Add a number to time(), which is the current time stamp as seconds from the Unix Epoch.
$twoweeks = time() + (2*7*24*60*60);
$thatasdate = date("d/m/Y", $twoweeks) ;
Check out date_add and the PHP DateTime model.
From the php manual page comes this fine example:
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
If you use this on your problem, you'd have
<?php
$dateofaddedimage = new DateTime('now'); //creates DateTime Model of today (and now)
$dateofimagedestroy = new DateTime('now'); //creates DateTime Model of today as well
$dateofimagedestroy->add(new DateInterval('P14D')); // adds 14 Days to the second date
The problem with what you are doing is that date() returns a string formatted to the date - not a proper date.
I would suggest either inserting a datetime into the database such as:
insert into yourTable (timeColumn) values (now());
This will insert the actual date. From there you can use mysql functions to add and subtract from this date.
Or using a timestamp in your code such as:
$uploadedTime=time();
From there you can either use PHP functions to add or subtract dates, or (as it is a timestamp) you can also use mysql functions to calculate what you need inside queries themselves.
I'm creating a forum, which also stores the time a post was sent, and I need to convert that into the user's timezone.
Now, the MySQL DataBase stores the time with UTC_TIMESTAMP() (in a column with the DATETIME type), and I created a little function from the code on http://www.ultramegatech.com/blog/2009/04/working-with-time-zones-in-php/ to convert the time to the user's timezone. This is the function:
function convertTZ($timestamp, $tz='UTC', $format='d-m-Y H:i:s') {
// timestamp to convert
$timestamp = strtotime($timestamp);
// the time formatting to use
$format = $format;
// the time zone provided
$tz = $tz;
// create the DateTimeZone object for later
$dtzone = new DateTimeZone($tz);
// first convert the timestamp into an RFC 2822 formatted date
$time = date('r', $timestamp);
// now create the DateTime object for this time
$dtime = new DateTime($time);
// convert this to the user's timezone using the DateTimeZone object
$dtime->setTimeZone($dtzone);
// print the time using your preferred format
$time = $dtime->format($format);
return $time;
}
And I made a test page at http://assets.momo40k.ch/timezones.php.
Now, when I insert a post into the DataBase at, say, 11:50 in my timezone (which is Europe/Rome), it inserts 09:50 in UTC, wich is correct, according to some online timezone converters.
But when I try to convert it back to Europe/Rome with the convertTZ() function, it returns 09:50, as if Europe/Rome is UTC. If I try converting it to a GMT+2:00 timezone, it returns 10:50. Can anyone fugure out why this is?
P.S: I'm not using the CONVERT_TZ() SQL function because my server does not support named timezones, so this function is my workaround.
Make sure your stored timestamps are UTC:
$date = new DateTime($timestamp, new DateTimeZone("UTC"));
$date->format(DATE_W3C); // does it gives the expected result ?
BTW your function can be simplified to this:
function convertTZ($timestamp, $tz='UTC', $format='d-m-Y H:i:s') {
$dtime = new DateTime($timestamp, new DateTimeZone("UTC"))
$dtime->setTimezone(new DateTimeZone("UTC"));
return $dtime->format($format);
}
MySQL always stores TIMESTAMP fields in UTC internally (that's the definition of a unix timestamp, in fact). So when you SELECT or UPDATE/INSERT/REPLACE, the time you get or set is always in the MySQL server's local time zone.
So a common mistake is to store UTC_TIMESTAMP(), which MySQL interprets as a local time and so the current time gets double-converted to UTC when it stores it internally in the field as a unix TIMESTAMP.
I have a PHP application that needs to support timezones. Now I am storing date and time values in the database as integers. So here is what I do.
// now create the DateTime object for this time and user time zone
$dtime = new DateTime($date_time, new DateTimeZone($time_zone));
$timestamp = $dtime->format('U');
What I don't understand is even if the person is in New Zealand (Pacific/Auckland) and the application stores this date: 24-12-2010 00:00:00 using the above code the value comes back as: 1293102000
Then using the exact same date/time and setting the time zone to London (Europe/London) I get this timestamp:1293148800
Why are the timestamps different? I thought the timestamp would be the same number of seconds as its the same date from the Unix Epoch?
If they are different that means when someone is searching the database for all records between 24-12-2010 00:00:00 and 24-12-2010 23:59:59 I need to use the users timezone for the creation of the timestamps and I must use the timezone to firstly create the timestamps.
Help!
Because timezone for New Zealand is +1300 UTC, where London is zero UTC, 13 x 3600seconds = 1293148800-1293102000
Since you already store as integer, you should always use zero UTC skip timezone when you construct $dtime
For testing
# date_create is procedural style
$obj = date_create('24-12-2010 00:00:00', new DateTimeZone('europe/london'));
echo $obj->format('U');
$obj = date_create('24-12-2010 00:00:00');
echo $obj->format('U');
Currently I store the time in my database like so: 2010-05-17 19:13:37
However, I need to compare two times, and I feel it would be easier to do if it were a unix timestamp such as 1274119041. (These two times are different)
So how could I convert the timestamp to unix timestamp? Is there a simple php function for it?
You're looking for strtotime()
You want strtotime:
print strtotime('2010-05-17 19:13:37'); // => 1274123617
Getting a unixtimestamp:
$unixTimestamp = time();
Converting to mysql datetime format:
$mysqlTimestamp = date("Y-m-d H:i:s", $unixTimestamp);
Getting some mysql timestamp:
$mysqlTimestamp = '2013-01-10 12:13:37';
Converting it to a unixtimestamp:
$unixTimestamp = strtotime('2010-05-17 19:13:37');
...comparing it with one or a range of times, to see if the user entered a realistic time:
if($unixTimestamp > strtotime("1999-12-15") && $unixTimestamp < strtotime("2025-12-15"))
{...}
Unix timestamps are safer too. You can do the following to check if a url passed variable is valid, before checking (for example) the previous range check:
if(ctype_digit($_GET["UpdateTimestamp"]))
{...}
If you're using MySQL as your database, it can return date fields as unix timestamps with UNIX_TIMESTAMP:
SELECT UNIX_TIMESTAMP(my_datetime_field)
You can also do it on the PHP side with strtotime:
strtotime('2010-05-17 19:13:37');
if you store the time in the database, why don't you let the database also give you the unix timestamp of it? see UNIX_TIMESTAMP(date), eg.
SELECT UNIX_TIMESTAMP(date) ...;
databases can also do date and time comparisons and arithmetic.