I have a user input where the user inputs time and date as '9.30am' and '01/02/2012'. I am trying to convert this to a unix timestamp to aid ordering when dragging the data back out of the database but strptime() is confusing me as I am unsure as to whether this is actually returning a unix timestamp that I need.
You can use: strtotime
PHP.net Example:
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
Using PHP's built-in DateTime class...
$objDate = DateTime::createFromFormat('H:ia d/m/Y', '9:30am 1/2/2012');
$timestamp = $objDate->getTimestamp();
...returns a Unix timestamp.
Documentation:
PHP DateTime Class
a. DateTime::createFromFormat
b. DateTime::getTimestamp
To add your variables, use it like so...
$objDate = DateTime::createFromFormat('H:ia d/m/Y', "$time $date");
$timestamp = $objDate->getTimestamp();
Or...
$time_date = sprintf("%s %s", $time, $date); // concatenates into a single var
$objDate = DateTime::createFromFormat('H:ia d/m/Y', $time_date);
$timestamp = $objDate->getTimestamp();
Note: Make sure that your variables conform with the following...
$time = hh:mm (and "am" or "pm" is appended)
$date = dd/mm/yyyy
You could use strtotime()
Call it by putting in your variables.
strtotime("9.30 1/2/2012");
http://php.net/manual/en/function.strtotime.php
$date = DateTime::createFromFormat('H:ia d/m/Y' '9:30am 1/2/2012');
$timestamp = $date->getTimestamp();
Is what you are looking for. http://www.php.net/datetime
Related
In my postgresql, the I have the following column named "created" that has the type timestamp with timezone
So I inserted the record according to the format as such which I believe is UTC.
2015-10-02 09:09:35+08
I am using php Carbon library so i did the following:
$date = Carbon\Carbon::parse('2015-10-02 09:09:35+08');
echo $date->->toDatetimeString();
//gives result as 2015-10-02 09:09:35
How can I use the library to echo the correct timezone which includes the adding of the +8 in the above datetime format? The timzezone that I am using is "Asia/Singapore".
The time should be printed to local timing which is 2015-10-02: 17:09:35:
Try this:
$timestamp = '2015-10-02 16:34:00';
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'Asia/Singapore');
Try this using standard PHP:
$raw = '2015-10-02 09:09:35+08';
$date = substr($raw,0,19);
$tzOffset = (strlen($raw) > 19) ? substr($raw,-3) : 0;
$timestamp = strtotime($date) + (60 * 60 * $tzOffset);
$localTime = date('Y-m-d H:i:s',$timestamp);
echo 'local time:['.$localTime.']';
The result is:
local time:[2015-10-02 17:09:35]
This will also work without a time zone offset or a negative one.
You can do this using native php without using Carbon:
$time = '2015-10-02 16:34:00+08';
$date = DateTime::createFromFormat('Y-m-d H:i:s+O', $time);
print $date->format('Y-m-d H:i:s') . PHP_EOL;
$date->setTimeZone(new DateTimeZone('Asia/Singapore'));
print $date->format('Y-m-d H:i:s') . PHP_EOL;
$date->setTimeZone(new DateTimeZone('Etc/UTC'));
print $date->format('Y-m-d H:i:s') . PHP_EOL;
I am generating next date using the following code:
$s1=date('d/M/Y', strtotime('+1 day'));
echo $s1;
for ex: Assume current date is 26/Aug/2014.
so above code generates 27/Aug /2014 and storing in varible $s1.
By using the varible s1 i want to create 28/Aug/2014. how to create?
I dont want to use '+2 day' in STRTOTIME function. I want to generate next day based on variable $s1.
You can do it all with strtotime() but you have to remember that strtotime assumes a USA date format when it see's a / forward slash as a seperator.
So before using $s1 you need to convert the / to a - so it assumes a sensible data format is being used.
$s1=date('d/M/Y', strtotime('+1 day'));
echo $s1.PHP_EOL;
// change date format as strtotime assumes USA dates
$date = strtotime( '+1 day', strtotime( str_replace('/','-',$s1) ) );
echo date('d/M/Y', $date);
When run on 26/Aug/2014 the result would be
27/Aug/2014
28/Aug/2014
The best way (using strtotime):
$tomorrow = strtotime('+1 day');
$twoDaysHence = strtotime('+1 day', $tomorrow);
echo date('d/M/Y', $tomorrow);
echo date('d/M/Y', $twoDaysHence);
In other words, leave your date variables in the form of UNIX timestamps as returned by strtotime until you need to display them. Because you can do calculations directly with them in this format. Once you format that to a date string, you'll have to convert them back into a malleable form first. strtotime doesn't recognise the format d/M/Y automatically, so that makes that all the harder. You should use DateTime in that case:
$tomorrow = date('d/M/Y', strtotime('+1 day'));
$timestamp = DateTime::createFromFormat('d/M/Y', $tomorrow);
$timestamp->modify('+1 day');
echo $timestamp->format('d/M/Y');
You can use something like following:
$newvariable = strtotime ('+2 day' , $s1);
this is a very simple part
$s1=date('d/M/Y', strtotime('+2 day'));
echo $s1;
and if you want then copy the value of $s1 in another variable
function date_addDate($text, $da=0, $ma=0, $ya=0, $ha=0)
{
$h=date('H',strtotime($text));
$d=date('d',strtotime($text));
$m=date('m',strtotime($text));
$y=date('Y',strtotime($text));
$fromTime =date("Y-m-d H:i:s", mktime($h+$ha, 0, 0, $m+$ma, $d+$da, $y+$ya));
return $fromTime;
}
$date = date("Y-m-d H:i:s");
// $da days
// $ma months
// $ya years
// $ha hours
echo date_addDate($date, $da=0, $ma=0, $ya=0, $ha=0);
//out put : current date
echo date_addDate($date, $da=2, $ma=0, $ya=0, $ha=0);
//out put : As you want
Try this
$s1=date('d/M/Y', strtotime('+1 day'));
echo $s1; echo "<br/>";
$date = strtotime(strtotime($s1). ' + 2 days');
$s2 = date('d/M/Y', $date);
echo $s2;
Now it's edited!! Check it!
What about using DateTime ?
$d1 = new DateTime(date('Y-m-d'));
$d1->format('d/m/Y'); // 26/08/2014
$d1->modify('+1 day');
$d1->format('d/m/Y'); // 27/08/2014
In my PHP program, I'm using $_SERVER to log the page's date visited:
$dateStamp = $_SERVER['REQUEST_TIME'];
The result is that the $dateStamp variable contains a Unix timestamp like:
1385615749
What's the simplest way to convert it into a human-readable date/time (with year, month, day, hour, minutes, seconds)?
This number is called Unix time. Functions like date() can accept it as the optional second parameter to format it in readable time.
Example:
echo date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
If you omit the second parameter the current value of time() will be used.
echo date('Y-m-d H:i:s');
Your functional approch to convert timestamp into Human Readable format are as following
function convertDateTime($unixTime) {
$dt = new DateTime("#$unixTime");
return $dt->format('Y-m-d H:i:s');
}
$dateVarName = convertDateTime(1385615749);
echo $dateVarName;
Output :-
2013-11-28 05:15:49
Working Demo
<?php
$date = new DateTime();
$dateStamp = $_SERVER['REQUEST_TIME'];
$date->setTimestamp($dateStamp);
echo $date->format('U = Y-m-d H:i:s') . "\n";
?>
you can try this
<?php
$date = date_create();
$dateStamp = $_SERVER['REQUEST_TIME'];
date_timestamp_set($date, $dateStamp);
echo date_format($date, 'U = D-M-Y H:i:s') . "\n";
?>
this code will work for you
$dateStamp = $_SERVER['REQUEST_TIME'];
echo date('d-M-Y H:i:s',strtotime($dateStamp));
REQUEST_TIME - It is unix timestamp - The timestamp of the start of the request.
$dateStamp = $_SERVER['REQUEST_TIME'];
echo date('d m Y', $dateStamp);
OR
$date = new DateTime($dateStamp);
echo $date->format('Y-m-d');
Im trying to add a certain amount of days to a timestmp using this in PHP:
$capturedDate = '2008-06-20';
$endDate = strtotime($capturedDate);
$endDate2 = strtotime('+1 day',$endDate);
echo $endDate2;
but its displaying: 1216526400
any ideas?
Try:
echo date("Y-m-d H:i:s",$endDate2);
Or (for just the date):
echo date("Y-m-d",$endDate2);
You can find documentation about how to format your string here: http://php.net/manual/en/function.date.php
You should be using DateTime for working with dates. It's timezone friendly.
$datetime = new DateTime('2008-06-20');
$datetime->modify('+1 day');
echo $datetime->getTimestamp();
strtotime() converts the date into a unix timestamp which is the number of seconds since January 1st 1970. If you want a date output you have to run the finished timestamp through date() first.
$capturedDate = '2008-06-20';
$endDate = strtotime($capturedDate.' +1 day');
echo date("Y-m-d", $endDate);
strtotime creates a Unix timestamp so if you want to be presented with a formatted date, you need to pass the timestamp as an argument to the date function as follows:
$capturedDate = '2008-06-20';
$endDate = strtotime($capturedDate);
$endDate2 = strtotime('+1 day',$endDate);
echo date('Y-m-d', $endDate2);
Additionally, there are a wide variety of parameters you can use in the date function if you want to display additional information.
e.g.: echo date('Y-m-d H:i:s', $endDate2); or echo date('Y-m-d h:i:s a', $endDate2);, etc.
Sooooo close, just take your timestamp and convert it back into date format using date("desired format",$endDate2);
DateTime is a very nice way to deal with dates. You can try like this:
$capturedDate = '2008-06-20';
$date = DateTime::createFromFormat('Y-m-d', $capturedDate)->modify('+1 day');
echo $date->getTimestamp();
I am in need of an easy way to convert a date time stamp to UTC (from whatever timezone the server is in) HOPEFULLY without using any libraries.
Use strtotime to generate a timestamp from the given string (interpreted as local time) and use gmdate to get it as a formatted UTC date back.
Example
As requested, here’s a simple example:
echo gmdate('d.m.Y H:i', strtotime('2012-06-28 23:55'));
Using DateTime:
$given = new DateTime("2014-12-12 14:18:00");
echo $given->format("Y-m-d H:i:s e") . "\n"; // 2014-12-12 14:18:00 Asia/Bangkok
$given->setTimezone(new DateTimeZone("UTC"));
echo $given->format("Y-m-d H:i:s e") . "\n"; // 2014-12-12 07:18:00 UTC
Try the getTimezone and setTimezone, see the example
(But this does use a Class)
UPDATE:
Without any classes you could try something like this:
$the_date = strtotime("2010-01-19 00:00:00");
echo(date_default_timezone_get() . "<br />");
echo(date("Y-d-mTG:i:sz",$the_date) . "<br />");
echo(date_default_timezone_set("UTC") . "<br />");
echo(date("Y-d-mTG:i:sz", $the_date) . "<br />");
NOTE: You might need to set the timezone back to the original as well
Do this way:
gmdate('Y-m-d H:i:s', $timestamp)
or simply
gmdate('Y-m-d H:i:s')
to get "NOW" in UTC.
Check the reference:
http://www.php.net/manual/en/function.gmdate.php
If you have a date in this format YYYY-MM-HH dd:mm:ss,
you can actually trick php by adding a UTC at the end of your "datetime string" and use strtotime to convert it.
date_default_timezone_set('Europe/Stockholm');
print date('Y-m-d H:i:s',strtotime("2009-01-01 12:00"." UTC"))."\n";
print date('Y-m-d H:i:s',strtotime("2009-06-01 12:00"." UTC"))."\n";
This will print this:
2009-01-01 13:00:00
2009-06-01 14:00:00
And as you can see it takes care of the daylight savings time problem as well.
A little strange way to solve it.... :)
Convert local time zone string to UTC string.
e.g. New Zealand Time Zone
$datetime = "2016-02-01 00:00:01";
$given = new DateTime($datetime, new DateTimeZone("Pacific/Auckland"));
$given->setTimezone(new DateTimeZone("UTC"));
$output = $given->format("Y-m-d H:i:s");
echo ($output);
NZDT: UTC+13:00
if $datetime = "2016-02-01 00:00:01", $output = "2016-01-31 11:00:01";
if $datetime = "2016-02-29 23:59:59", $output = "2016-02-29 10:59:59";
NZST: UTC+12:00
if $datetime = "2016-05-01 00:00:01", $output = "2016-04-30 12:00:01";
if $datetime = "2016-05-31 23:59:59", $output = "2016-05-31 11:59:59";
https://en.wikipedia.org/wiki/Time_in_New_Zealand
If you don't mind using PHP's DateTime class, which has been available since PHP 5.2.0, then there are several scenarios that might fit your situation:
If you have a $givenDt DateTime object that you want to convert to UTC then this will convert it to UTC:
$givenDt->setTimezone(new DateTimeZone('UTC'));
If you need the original $givenDt later, you might alternatively want to clone the given DateTime object before conversion of the cloned object:
$utcDt = clone $givenDt;
$utcDt->setTimezone(new DateTimeZone('UTC'));
If you only have a datetime string, e.g. $givenStr = '2018-12-17 10:47:12', then you first create a datetime object, and then convert it. Note this assumes that $givenStr is in PHP's configured timezone.
$utcDt = (new DateTime($givenStr))->setTimezone(new DateTimeZone('UTC'));
If the given datetime string is in some timezone different from the one in your PHP configuration, then create the datetime object by supplying the correct timezone (see the list of timezones PHP supports). In this example we assume the local timezone in Amsterdam:
$givenDt = new DateTime($givenStr, new DateTimeZone('Europe/Amsterdam'));
$givenDt->setTimezone(new DateTimeZone('UTC'));
As strtotime requires specific input format, DateTime::createFromFormat could be used (php 5.3+ is required)
// set timezone to user timezone
date_default_timezone_set($str_user_timezone);
// create date object using any given format
$date = DateTime::createFromFormat($str_user_dateformat, $str_user_datetime);
// convert given datetime to safe format for strtotime
$str_user_datetime = $date->format('Y-m-d H:i:s');
// convert to UTC
$str_UTC_datetime = gmdate($str_server_dateformat, strtotime($str_user_datetime));
// return timezone to server default
date_default_timezone_set($str_server_timezone);
I sometime use this method:
// It is not importnat what timezone your system is set to.
// Get the UTC offset in seconds:
$offset = date("Z");
// Then subtract if from your original timestamp:
$utc_time = date("Y-m-d H:i:s", strtotime($original_time." -".$offset." Seconds"));
Works all MOST of the time.
http://php.net/manual/en/function.strtotime.php or if you need to not use a string but time components instead, then http://us.php.net/manual/en/function.mktime.php
With PHP 5 or superior, you may use datetime::format function (see documentation http://us.php.net/manual/en/datetime.format.php)
echo strftime( '%e %B %Y' ,
date_create_from_format('Y-d-m G:i:s', '2012-04-05 11:55:21')->format('U')
); // 4 May 2012
try
echo date('F d Y', strtotime('2010-01-19 00:00:00'));
will output:
January 19 2010
you should change format time to see other output
General purpose normalisation function to format any timestamp from any timezone to other.
Very useful for storing datetimestamps of users from different timezones in a relational database. For database comparisons store timestamp as UTC and use with gmdate('Y-m-d H:i:s')
/**
* Convert Datetime from any given olsonzone to other.
* #return datetime in user specified format
*/
function datetimeconv($datetime, $from, $to)
{
try {
if ($from['localeFormat'] != 'Y-m-d H:i:s') {
$datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
}
$datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
$datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
return $datetime->format($to['localeFormat']);
} catch (\Exception $e) {
return null;
}
}
Usage:
$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta'];
$to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC'];
datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"
As an improvement on Phill Pafford's answer (I did not understand his 'Y-d-mTG:i:sz' and he suggested to revert timezone).
So I propose this (I complicated by changing the HMTL format in plain/text...):
<?php
header('content-type: text/plain;');
$my_timestamp = strtotime("2010-01-19 00:00:00");
// stores timezone
$my_timezone = date_default_timezone_get();
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date)\n";
// changes timezone
date_default_timezone_set("UTC");
echo date("Y-m-d\TH:i:s\Z", $my_timestamp)."\t\t (ISO8601 UTC date)\n";
echo date("Y-m-d H:i:s", $my_timestamp)."\t\t (your UTC date)\n";
// reverts change
date_default_timezone_set($my_timezone);
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date is back)\n";
?>
alternatively you can try this:
<?php echo (new DateTime("now", new DateTimeZone('Asia/Singapore')))->format("Y-m-d H:i:s e"); ?>
this will output :
2017-10-25 17:13:20 Asia/Singapore
you can use this inside the value attribute of a text input box if you only want to display a read-only date.
remove the 'e' if you do not wish to show your region/country.
Follow these steps to get UTC time of any timezone set in user's local system (This will be required for web applications to save different timezones to UTC):
Javascript (client-side):
var dateVar = new Date();
var offset = dateVar.getTimezoneOffset();
//getTimezoneOffset - returns the timezone difference between UTC and Local Time
document.cookie = "offset="+offset;
Php (server-side):
public function convert_utc_time($date)
{
$time_difference = isset($_COOKIE['offset'])?$_COOKIE['offset']:'';
if($time_difference != ''){
$time = strtotime($date);
$time = $time + ($time_difference*60); //minutes * 60 seconds
$date = date("Y-m-d H:i:s", $time);
} //on failure of js, default timezone is set as UTC below
return $date;
}
..
..
//in my function
$timezone = 'UTC';
$date = $this->convert_utc_time($post_date); //$post_date('Y-m-d H:i:s')
echo strtotime($date. ' '. $timezone)