I have something in my database that shows the time when the users who signed up on my recorded .. When the person makes the user saves the script (time ();) currently in the database under the variable name "REGTIM".
If I use echo to print it out, I get for example:
1375202508
How can I make this a date if it is possible? or for example as mentioned below.
for example: 08/06/2013 2:11
You can use date() function with timestamp mention in the second argument,
date ( string $format [, int $timestamp = time() ] )
or in your case:
date('m/d/Y H:m', 1375202508);
you can read more on http://php.net/manual/en/function.date.php
You could have got the answer to that with a little bit of searching. But here you go:
echo date('m/d/Y h:m', 1375202508); // 07/30/2013 10:07 -- 12-hour format
echo date('m/d/Y H:m', 1375202508); // 07/30/2013 22:07 -- 24-hour format
See the documentation for more options: http://php.net/manual/en/function.date.php
that's probably just a unix timestamp, so use FROM_UNIXTIME() and DATE_FORMAT() to do the conversion/formatting inside your query, or use date() in PHP to work with the timestamp directly.
e.g.
echo date('d/m/Y h:m', $timestamp)
or
SELECT DATE_FORMAT('%d/%m/%y %h:%m', FROM_UNIXTIME(REGTIM))
Related
I am trying to add 1 hour to a timestamp field fetched from database using the following code.
date($ls['created_at'], strtotime('+1 hour'));
However, this doesn't seem to work. It returns the same time as in database. Am I missing something? Or, is the code deprecated? What is the proper solution?
You need to give it the correct syntax to use this,
You need to send the time to change with the change itself in the function - for example (using date for wanted format):
$date = "22-02-2021 14:22:22";
echo date("d-m-Y H:i:s", strtotime($date.' +1 hour'));
This will return:
22-02-2021 15:22:22
Same as this:
echo date("d-m-Y H:i:s", strtotime("22-02-2021 14:22:22 + 1 hour"));
The idea is that you strtotime receives the date and data to change in one string like this :
echo strtotime("22-02-2021 14:22:22 + 2 hour");
Will return:
1614010942
Here I removed the Date Format so I received a unix timestamp format
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.
I have a MySQL DB table with a column named "timestamp", a type of timestamp, and attribute of on update CURRENT_TIMESTAMP and a default of CURRENT_TIMESTAMP.
If I add a record to the table, specifying other values, but not the timestamp, then the timestamp is automatically added like 2016-12-28 17:02:26.
In PHP I query the table using the following query
SELECT * FROM history WHERE user_id = 9 ORDER BY timestamp ASC
The result of the query is saved into $rows and I use a foreach to create an array with some of the other values formatted. I am attempting to format the time stamp to UK type 24-hour date time: dd/mm/yy, HH:MM:SS.
I have tried both the date() and strftime() functions as follows:
$formatted_datetime = strftime("%d %m %y %H %M %S", $row["timestamp"]);
$formatted_datetime = date("d/m/y, H:i:s", $row["timestamp"]);
Both of these result in the following notice and the date time being output incorrectly like 01 01 70 00 33 36:
Notice: A non well formed numeric value encountered in /home/ubuntu/workspace/pset7/public/history.php on line 20
I am new to PHP and MySQL and so far none of the other questions or documentation I have seen have successfully addressed performing this conversion.I do not understand why strftime() does not work, nor how to do this properly?
To do this the OO (and most flexible) way use DateTime class and use the static createFromFormat method to instantiate a new DateTime object:
$new_datetime = DateTime::createFromFormat ( "Y-m-d H:i:s", $row["timestamp"] );
Now you can use the $new_datetime object to generate any string representation you'd like by calling the object's format method:
echo $new_datetime->format('d/m/y, H:i:s');
To boot, you since you've a DateTime object you can now also to any manner of transformation (like shifting timezones or adding days), comparison (greater or less than another DateTime), and various time calculations (how many days/months/etc... between this and another DateTime).
DateTime:http://php.net/manual/en/class.datetime.php
Learn it. Love it. Live it.
Normally in MySQL date timestamp save time as YYYY-MM-DD HH:MM:SS (2016-12-20 18:36:14) formate you can easily convert them as your wish using date formate but have to convert your input to time first. Following will do the trick
$formatted_datetime = date("d/m/y, H:i:s", strtotime($row["timestamp"]));
Why not make MySQL do the work? And do you really want mm/dd/yy, not dd/mm/yy?
SELECT *, DATE_FORMAT(timestamp, '%m/%d/%y, %T') formatted_date FROM ....
Then you can extract the formatted date as $row['formatted_date'].
See https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
The date is of timestamp type which has the following format: ‘YYYY-MM-DD HH:MM:SS’ or ‘2008-10-05 21:34:02.’
$res = mysql_query("SELECT date FROM times;");
while ( $row = mysql_fetch_array($res) ) {
echo $row['date'] . "
";
}
The PHP strtotime function parses the MySQL timestamp into a Unix timestamp which can be utilized for further parsing or formatting in the PHP date function.
Here are some other sample date output formats that may be of practical use:
echo date("F j, Y g:i a", strtotime($row["date"])); // October 5, 2008 9:34 pm
echo date("m.d.y", strtotime($row["date"])); // 10.05.08
echo date("j, n, Y", strtotime($row["date"])); // 5, 10, 2008
echo date("Ymd", strtotime($row["date"])); // 20081005
echo date('\i\t \i\s \t\h\e jS \d\a\y.', strtotime($row["date"])); // It is the 5th day.
echo date("D M j G:i:s T Y", strtotime($row["date"])); // Sun Oct 5 21:34:02 PST 2008
I would use the Carbon class and its String Formatting
$carbon = Carbon::instance('2016-12-28 17:02:26');
Then you can format it the way you want.
So I have a field in my database called 'DateTime' and the following lines of code:
echo "Date/Time: ";
echo $row['DateTime'];
How do I format it so that instead of being like this:'2013-02-07 22:14:56', it will be like this: '07/02/13 - 22:14'
Thanks.
Alternatively you could use:
DateTime::createFromFormat('Y/m/d H:i:s',$row['DateTime']); this will give you a datetime object, which are quite nice to work with.
Another alternative would be to have MySQL format the DATETIME value as a string in the desired format, using the DATE_FORMAT function.
SELECT DATE_FORMAT(`DateTime`,'%d/%m/%y - %H:%i') AS `DateTime`
...
No change required to your PHP code except for the SQL text sent to the database server.
This approach can very efficient, and reduce the amount of code you need, if all you are doing with this string is displaying it. If you are doing any sort of manipulation on this value, then casting the string value returned from MySQL resultset into a datetime object is probably a better way to go.
A demonstration of the DATE_FORMAT function:
SELECT DATE_FORMAT('2013-02-07 22:14:56','%d/%m/%y - %H:%i') AS `DateTime`
DateTime
----------------
07/02/13 - 22:14
how to output date into Year textbox Month textbox Day textbox
$book_date = $myrow["Publication_Day"];
$book_year = Date("Y", strtotime($book_date));
$timestamp contains ur date & time in any format.....................
date('Y/m/d - H:i',strtotime($timeStamp));
echo date('d/m/y H:i', strtotime($row['DateTime']));
See date and strtotime for more detail on the functions from the docs
$mytime = strtotime('2013-06-07 22:14:56');
$newDate = date('m/d/y - G:i', $mytime);
echo $newDate;
Here's an alternative using DateTime. If you're working with timezones this code can be easily modified to handle that.
$datetime = new DateTime('2013-02-07 22:14:56');
echo $datetime->format('d/m/y H:i');
See it in action
I want to convert this date ( 02-12-2010) mm-dd-yyyy to time format
ie
to 02-12-2010 0 hours 0 minutes and 0 seconds
i have user time and date functions but when i refresh the page its value is changing as per the time.
i need that to be fixed
also i want to convert this date (01-24-2009) to time format.
please help me
Thanks
Use the strtotime function to convert an existing date/time string into a timestamp for the date function.
$new_date = date('m-d-Y h:i:s', strtotime('02-12-2010'));
The reason that your date keeps updating with the current time is that the date() function uses the current system's timestamp by default when no second parameter is provided.
Use the date_parse_from_format () API function to transform your given format to an array. E.g.
$date = "02-12-2010";
$dateArr = date_parse_from_format("d-m-Y", $date);
Output it with something like:
$output = $dateArr['day'] . '-' . $dateArr['month'] '-' . $dateArr['year'];
You can use the strtotime function eg:
$mydate = date('m-d-Y h:i:s', strtotime('02-12-2010'));