Recognize date format - php

What date format is this?
2012-06-08dT00:00:00Z
And how can i convert a timestamp in php to this date format?

$dt = new DateTime('2012-06-08T00:00:00Z'); //with no 'd'
$timestamp = $dt->format('U');
If you must have the 'd', then:
$dt = DateTime::createFromFormat('Y-m-d??H:i:s?', '2012-06-08dT00:00:00Z');
$timestamp = $dt->format('U');
ETA: timestamp -> your format
$dt = new DateTime('#1339124400'); //the # indicates the following number is a timestamp
$isoformat= $dt->format('Y-m-d\TH:i:sZ'); //leave out the 'd' and escape the 'T'

here is something for you to start from:
$date = "2012-06-08dT01:02:03Z";
// parse the date correctly
$parsed_date = date_parse_from_format('Y-m-d H:i:s ', $date);
print_r($parsed_date);
// Make time from parsed date
$old_date = mktime($parsed_date['hour'], $parsed_date['minute'], $parsed_date['second'], $parsed_date['month'], $parsed_date['day'], $parsed_date['year']);
$now_date = time();
// a silly way to print that parsed date into the original way as before
echo date("Y-m-d", $old_date) . 'dT' . date("H:i:s", $old_date) . 'Z';
echo "\n";
// a silly way to print current date/time in that format
echo date("Y-m-d", $now_date) . 'dT' . date("H:i:s", $now_date) . 'Z';

Related

How to sum hours with existing datetime in PHP?

I have two fields which store data like 2018-03-26 11:20:35 and 02:25:10(2 hours 25 minutes and 10 seconds) first data is date and time. second one is only time. I want to sum it and finally my result should 2018-03-26 13:45:45
How to do that in php code?
I have tried this way:
<?php
$date = '2018-03-26 11:20:35';
//echo $date;
//echo "<br>";
$hours = '02:25:10'; /* this data dynamic */
$sumTime = strtotime($date) + strtotime($hours);
$new_time = date("Y-m-d H:i:s", $sumTime);
echo $new_time;
Output:
Warning: date() expects parameter 2 to be integer, float given in C:\my-project-path\test.php on line 7
Here's a simple solution, some checks are skipped:
// convert your date to DateTime object
$date = '2018-03-26 11:20:35';
$dt = new DateTime($date);
// convert your period to DateInterval
$hours = '02:25:10'; /* this data dynamic */
$parts = explode(':', $hours);
$interval = new DateInterval('PT' . (int)$parts[0] . 'H' . $parts[1] . 'M' . $parts[2] . 'S');
// Add interval to date
$dt->add($interval);
// Format date as you need
echo $dt->format('Y-m-d H:i:s');
You could create a duration in seconds by comparing today at "00:00:00" and today at $hours. Actually, strtotime($hours) returns the timestamp of today at $hours, so, the addition of the two timestamp don't give the expected result.
If $hours is lesser than 24 hours, you could use:
$date = '2018-03-26 11:20:35';
$hours = '02:25:10';
$d0 = strtotime(date('Y-m-d 00:00:00'));
$d1 = strtotime(date('Y-m-d ').$hours);
$sumTime = strtotime($date) + ($d1 - $d0);
$new_time = date("Y-m-d H:i:s", $sumTime);
echo $new_time;
Outputs:
2018-03-26 13:45:45
You should check DateTime::add:
http://php.net/manual/en/datetime.add.php
http://php.net/manual/en/datetime.examples-arithmetic.php
Example:
<?php
// Convert h:m:s format to PThHmMsS format
sscanf('02:25:10', '%d:%d:%d', $hour, $minute, $second);
$intervalSpec = sprintf('PT%dH%dM%dS', $hour, $minute, $second);
$datetime = new DateTimeImmutable('2018-03-26 11:20:35');
$newDatetime = $datetime->add (new DateInterval($intervalSpec));
echo $newDatetime->format(DateTime::W3C);
It could be done with some simple string manipulation:
$dt = new DateTime("$date UTC");
$modify = preg_replace('/:/', ' hours ', $hours, 1);
$modify = preg_replace('/:/', ' minutes ', $modify, 1);
$modify .= ' seconds';
$dt->modify($modify);
demo
If you have MySQL as your data storage, you could do:
DATE_ADD(field1, INTERVAL field2 HOUR_SECOND)
demo
you can do something like:
$hour = $hours->format('H'); //This way you get a string which contains the hours
$date->modify('+'.$hour.' hour'); //you modify your date adding the hours
I'm assuming you only need the hours, and not minutes and seconds
EDIT:
you can do like that using regexp
$date = new \DateTime('2018-03-26 11:20:35');
$hours ='02:25:10';
preg_match("/^([0-9].*):([0-9].*):([0-9].*)/",$hours,$matches);
$date->modify('+'.$matches[1].' hour');
$date->modify('+'.$matches[2].' minute');
echo $date->modify('+'.$matches[3].' second')->format('Y-m-d H:i:s');

How can force change the day in datetime in php

$date = date_create('2013-10-27');// This is the date that inputed in textbox and that format is (Y-m-d)
$date = date_create('2013-10-10');// and if i click the button i want to force change the 27 to 10?
Should i use date_modify and do some loop or there's other way to change it in easy way rather than looping.
$in = date_create('2013-10-27');
// example 1
$out = date_create($in->format('Y-m-10'));
echo $out->format('Y-m-d') . "\n";
// example 2
$out = clone $in;
$out->setDate($out->format('Y'), $out->format('m'), 10);
echo $out->format('Y-m-d') . "\n";
// example 3
$out = clone $in;
$out->modify((10 - $out->format('d')) . ' day');
echo $out->format('Y-m-d') . "\n";
Demo.
You can use the native PHP "date_date_set" function to make this change.
$date = date_create('2013-10-27');
echo $date->format('Y-m-d');
2013-10-27
date_date_set($date,
date_format($date, 'Y'),
date_format($date, 'm'),
10);
echo $date->format('Y-m-d');
2013-10-10
Or using the Object-Oriented style:
$date = new DateTime('2013-10-27');
echo $date->format('Y-m-d');
2013-10-27
$date->setDate($date->format('Y'), $date->format('m'), 10);
echo $date->format('Y-m-d');
2013-10-10
Note: If you're just trying to modify the value of a day on the date that comes from a submitted <input> from a <form>. You could try these steps:
$date = '2013-10-27'; // pass the value of input first.
$date = explode('-', $date); // explode to get array of YY-MM-DD
//formatted results of array would be
$date[0] = '2013'; // YY
$date[1] = '10'; // MM
$date[2] = '17'; // DD
// when trigger a button to change the day value.
$date[2] = '10'; // this would change the previous value of DD/Day to this one. Or input any value you want to execute when the button is triggered
// then implode the array again for datetime format.
$date = implode('-', $date); // that will output '2013-10-10'.
// lastly create date format
$date = date_create($date);
$date = date("Y-m-d", strtotime("2013-10-10"));
Updated:
to force to change the day from 27 to 10
1) get the year and month
$date = date("Y-m-", strtotime( $_POST['user_selected_date'] ));
2) append your day
$date .= '10';
Also you can finish it in ONE step
$date = date("Y-m-10", strtotime( $_POST['user_selected_date'] ));
Use PCRE Function
$date = '2013-10-27';
$new_date = preg_replace("/\d{2}$/", "10", $date);
preg_replace manual

PHP - Convert GMT Timestamp

I'm receiving some data from an HTTP POST which includes what is labelled a GMT Timestamp:
<gmt_timestamp>201308031525</gmt_timestamp>
I then need to take this timestamp and convert it to this format:
MM/DD/YYYY HH:MM
So far I've been trying this:
$ts = $_GET['timestamp'];
$date = DateTime::createFromFormat('ymdHi', $ts);
$fmTimestamp = $date->format('m/d/Y h:i:s A');
but that generates a "PHP Fatal error: Call to a member function format() on a non-object" for the 2nd line. Any idea what I'm doing wrong?
You have a bug in this line:
$date = DateTime::createFromFormat('ymdHi', $ts);
You need an uppercase Y for the year:
$date = DateTime::createFromFormat('YmdHi', $ts);
A lowercase y indicates "A two digit representation of a year", whereas you need Y ("A full numeric representation of a year, 4 digits"). See the docs here.
You also need to set the timezone before you begin:
date_default_timezone_set('UTC');
(PHP does have a GMT timezone, but it shouldn't be used. UTC behaves the same as GMT within PHP.)
Edit
To get your desired output format of:
MM/DD/YYYY HH:MM
you need to do:
$fmTimestamp = $date->format('m/d/Y H:i');
Also, since you're "receiving some data from an HTTP POST", you need to use $_POST instead of $_GET:
$ts = $_POST['timestamp'];
So the complete code is:
date_default_timezone_set('UTC');
$ts = $_POST['timestamp'];
$date = DateTime::createFromFormat('YmdHi', $ts);
$fmTimestamp = $date->format('m/d/Y H:i');
Keep it simple stupid.
$input = $_GET['timestamp']; // 201308031525
$year = (int)substr($input,0,4);
$month = (int)substr($input,4,2);
$date = (int)substr($input,6,2);
$hour = (int)substr($input,8,2);
$minute = (int)substr($input,10);
$date_obj = new DateTime($year . '-' . $month . '-' . $date .' ' . $hour . ':' . $minute);
echo $date_obj->format('m/d/Y h:i:s A');
and the output is:
08/03/2013 03:25:00 PM
You are not instantiating the object you are trying to use.
Try this approach instead:
$date = new DateTime;
$date->createFromFormat('ymdHi', $ts);
$fmTimestamp = $date->format('m/d/Y h:i:s A');
This is untested, just saying ...

Simple PHP time format not working!

I have the following value:
30/05/2010 # 09:15:15
I need to convert it to Y-m-d H:i:s.
I've tried:
$date = "30/05/2010 # 09:15:15";
$formatteddate = date("Y-m-d H:i:s", time($date));
echo $formatteddate;
I end up with a value dated 1970. I've also tried strtotime.
Can anyone point out what I'm missing?
The time() function does not have any parameters which is why it is going to give you an error.
I have tried to use strtotime() thinking that may work, but it is not. I will update my answer when I find something that works. However, first thing is that time() will not work.
Edit: As Phil just beat me to seconds before:
$date = str_replace("# ", "", "30/05/2010 # 09:15:15");
$date = str_replace("/", "-", $date);
$formatteddate = date("Y-m-d H:i:s", strtotime($date));
echo $formatteddate;
Example is here: http://codepad.org/heph1PG0
If you're using PHP 5.3, try DateTime::createFromFormat(), eg
$dt = DateTime::createFromFormat('d/m/Y # H:i:s', $date);
If not, strtotime() may work but you'll need to get rid of the # symbol and change the forward slashes to hyphens (if that's an EU / AU date), eg
$time = strtotime(str_replace(array('#', '/'), array('', '-'), $date));
Edit:
To display the dates in the format you want, use
echo $dt->format('Y-m-d H:i:s'); // for DateTime
echo date('Y-m-d H:i:s', $time); // for strtotime
You have a bit of an odd format there... try date_parse_from_format.
http://www.php.net/manual/en/function.date-parse-from-format.php
$date = "30/05/2010 # 09:15:15";
$d = date_parse_from_format('m/d/Y # h:i:s', $date);
$formatted_date = "{$d['year']}-{$d['month']}-{$d['day']} {$d['hour']}:{$d['minute']}:{$d['second']}";
You have a very odd date format, so strtotime will have trouble. Instead we will use strptime which accepts a custom format:
$date = "30/05/2010 # 09:15:15";
$format = "%d/%m/%Y # %T";
$ftime = strptime($date, $format);
$timestamp = mktime(
$ftime['tm_hour'],
$ftime['tm_min'],
$ftime['tm_sec'],
// Because this is 0-11
$ftime['tm_mon'] + 1,
$ftime['tm_mday'],
// Because this is years since 1900
$ftime['tm_year'] + 1900
);
$formatteddate = date("Y-m-d H:i:s", $timestamp);
echo $formatteddate;
Result:
2010-05-30 09:15:15
If you're using PHP 5.3.0 or greater, you can use date_parse_from_format() to parse your custom formatted date.
If you're stuck on an older version of PHP, you'll have to parse it yourself. I've verified that this works:
<?php
function reformatDate($date) {
$matches = array();
if (!preg_match('/^(\d\d)\/(\d\d)\/(\d{4})\s*#\s*(\d\d):(\d\d):(\d\d)$/', $date, $matches)) {
throw new InvalidArgumentException('Invalid date supplied: ' . $date);
}
$day = $matches[1];
$month = $matches[2];
$year = $matches[3];
$hour = $matches[4];
$minute = $matches[5];
$second = $matches[6];
if ($day < 1 || $day > 31 || $month < 1 || $month > 12 || $hour > 24 || $minute > 60 || $second > 60) {
throw new InvalidArgumentException('Invalid date supplied: ' . $date);
}
return "$year-$month-$day $hour:$minute:$second";
}
echo reformatDate("30/05/2010 # 09:15:15");
?>
for all of you guyz date function will not format dates like 01/01/2045, this is something php restriction for dates having large years i.e 2039.
Try Like this...
<?php
$date = date_create('01-01-2001');
echo date_format($date, 'Y-m-d H:i:s');
?>

Simplest way to increment a date in PHP?

Say I have a string coming in, "2007-02-28", what's the simplest code I could write to turn that into "2007-03-01"? Right now I'm just using strtotime(), then adding 24*60*60, then using date(), but just wondering if there is a cleaner, simpler, or more clever way of doing it.
A clean way is to use strtotime()
$date = strtotime("+1 day", strtotime("2007-02-28"));
echo date("Y-m-d", $date);
Will give you the 2007-03-01
It's cleaner and simpler to add 86400. :)
The high-tech way is to do:
$date = new DateTime($input_date);
$date->modify('+1 day');
echo $date->format('Y-m-d');
but that's really only remotely worthwhile if you're doing, say, a sequence of transformations on the date, rather than just finding tomorrow.
You can do the addition right inside strtotime, e.g.
$today="2007-02-28";
$nextday=strftime("%Y-%m-%d", strtotime("$today +1 day"));
Another way is to use function mktime(). It is very useful function...
$date = "2007-02-28";
list($y,$m,$d)=explode('-',$date);
$date2 = Date("Y-m-d", mktime(0,0,0,$m,$d+1,$y));
but I think strtotime() is better in that situation...
The simplest way...
echo date('Y-m-d',strtotime("+1 day")); //from today
OR from specified date...
echo date('Y-m-d',strtotime("+1 day", strtotime('2007-02-28')));
Hello you can try this below especially if you are french
$date = date('l j F Y');
#increment the date
$date2 = date('l j F Y', strtotime("+7 day"));
to translate in french you can use the setlocale() function or the function below :
function fr_date($date){
$date = explode(' ', $date);
$date = str_replace('Monday','Lundi',$date);
$date = str_replace('Tuesday','Mardi',$date);
$date = str_replace('Wednesday','Mercredi',$date);
$date = str_replace('Thursday','Jeudi',$date);
$date = str_replace('Friday','Vendredi',$date);
$date = str_replace('Saturday','Samedi',$date);
$date = str_replace('Sunday','Dimanche',$date);
$date = str_replace('January','Janvier',$date);
$date = str_replace('February','Février',$date);
$date = str_replace('March','Mars',$date);
$date = str_replace('April','Avril',$date);
$date = str_replace('May','Mai',$date);
$date = str_replace('June','Juin',$date);
$date = str_replace('July','Juillet',$date);
$date = str_replace('August','Août',$date);
$date = str_replace('September','Septembre',$date);
$date = str_replace('October','Octobre',$date);
$date = str_replace('November','Novembre',$date);
$date = str_replace('December','Décembre',$date);
$date = implode(' ',$date);
return $date;
}
$your_date = strtotime("1month", strtotime(date("Y-m-d")));
$new_date = date("Y-m-d", $your_date++);
use strtotime() With date Formate
echo date('Y-m-d', strtotime('2007-02-28' . ' +1 day'));
$early_start_date = date2sql($_POST['early_leave_date']);
$date = new DateTime($early_start_date);
$date->modify('+1 day');
$date_a = new DateTime($early_start_date . ' ' . $_POST['start_hr'] . ':' . $_POST['start_mm']);
$date_b = new DateTime($date->format('Y-m-d') . ' ' . $_POST['end_hr'] . ':' . $_POST['end_mm']);
$interval = date_diff($date_a, $date_b);

Categories