Formatting Duration From String in PHP - php

i want to calculate different dates from sting, string format is (01:50:30),
For Example:
1: (01:35:00)
2: (04:45:50)
3: (02:35:36)
4: (01:00:00)
5: (06:35:47)
How to calculate these stings with date format?

You can use DateTime
<?php
date_default_timezone_set('America/Los_Angeles');
$time = DateTime::createFromFormat('H:i:s', '12:05:59');
var_dump($time);
$time->modify('5 minutes');
$time->modify('1 hour');
$time->modify('-30 seconds');
var_dump($time);

You won't be able to work out the date solely from the times you have provided, you can turn it into a DateTime object which will set the current date to today and used the times you provided as the time.
For example:
$time = '(01:35:00)';
$date = DateTime::createFromFormat('(' . 'H:i:s' . ')', $time);
echo $date->format('Y-m-d H:i:s');
Will output:
2016-01-25 01:35:00
You can then easily manipulate the DateTime object as you need. The full documentation can be found in the PHP manual:
http://php.net/manual/en/class.datetime.php

Related

Convert Now and Ten Minutes Ago to Different Timezone

I would like to convert the timestamps from ten minutes ago and now to match the following format:
2018-09-23T04:47:07.237
Here are the timestamps I'd like to convert to match the above format:
$now = date('m/d/y g:i a');
$now = strtotime($now);
$ten_minutes_ago = strtotime('-10 minutes');
How can I do this? Thanks!
Use date_format function instead. You don't need to convert to UNIX timestamp using strtotime function. Instead use DateTime library
Check the following (Rextester Demo):
$now = new DateTime(); // create a datetime object
$sub = new DateInterval("PT10M"); // Interval of 10 mins
$ten_minutes_ago = new DateTime();
$ten_minutes_ago->sub($sub); // subtract 10 minutes
// changed formats
$now_changed = date_format($now, DATE_ISO8601);
$ten_minutes_ago_changed = date_format($ten_minutes_ago, DATE_ISO8601);
// print output
echo $now_changed; //2018-09-23T02:58:25-0400
echo $ten_minutes_ago_changed; // 2018-09-23T02:48:25-0400
Details:
The date_format() function returns a date formatted according to the specified format.
DATE_ISO8601 - ISO-8601 (example: 2013-04-12T15:52:01+0000)
You can check for more formatting options here.
Here is how I would do what you are asking for.
If your data is in a string. Here is the only line of code you need:
$date = date('m/d/y g:i a'); //Gets a date string.
echo substr(date('Y-m-d\TH:i:s.u', strtotime($date . ' -10 minutes')), 0, -3); // PHP < 7.0.0
//echo date('Y-m-d\TH:i:s.v', strtotime($date . ' -10 minutes')); //PHP > 7.0.0
This will produce:
Ex.
09/23/18 12:13 am
To
2018-09-23T00:03:00.000
One thing to note here. The microseconds will always be zeros if your original input date is a string and in the format m/d/y g:i a that you have specified. The reason being is that there is no millisecond information to be had from the date string.
If you create you input date as a dateTime object, the object will be able to keep track of the microseconds for you.

adding one day to a custom formatted date string

I have a string in the format YYYYMMDDHH24MISS that is year, month, day, hours, minutes, seconds. I want to convert this to a date, add one day to it and return it in the same format. Sounds simple but I am unable to get this to work. I have tried a number of different ways where $field3 contains the date string for example:
$end_date = strtotime(substr($field3,1,8));
$date_interval = DateInterval::createFromDateString('1 day');
$new_end_date = date_add($end_date, $date_interval);
$field3 = ($new_end_date->format('YYYYMMDD')).substr($field3,8,6);
In this example $new_end_date contains "false".
Example date time string: 20170912124159 being 12/09/2017 12:41:59
The format of your input string can be parsed by the constructor of class DateTime (and date_create() and strtotime()) without problems.
$date = new DateTime('20170912124159');
$date->add(new DateInterval('P1D'));
echo($date->format('Y-m-d H:i:s'));
# The output is:
# 2017-09-13 12:41:59
You can, as well, format the date as string using the format YmdHis to get the modified date in the same format as the input string.
echo($date->format('YmdHis'));
# 20170913124159
Read about DateTime and DateInterval.
You can try something like this:
$date = DateTime::createFromFormat('YmdHis', '20170912131313');
$date->add(new DateInterval('P10D'));
echo $date->format('Y-m-d');
For more information: http://php.net/manual/en/datetime.add.php
Please try this
$date = date("Y/m/d H:i:s"); // or '2017/09/30 20:24:00'
$ndate = date('Y/m/d H:i:s', strtotime($date . ' +1 day'));
echo 'date after adding 1 day: ' . $ndate;

PHP date and time from an xml import

I have an xml file where the date stored in this format:
<sun rise="2014-05-30T02:51:30" set="2014-05-30T18:31:22"/>
My php process this value to a variable named $sunrise
2014-05-30T02:51:30
But my timezone is +2 so I have to add 2 more hours.
The only problem with this its just a string.
I dont have any idea to how to convert it to date.
Since you already got the time inside that element (2014-05-30T02:51:30) you could just use strtotime() or alternatively, you could also use DateTime + DateInterval to add 2 more hours. Consider this example:
$sunrise = '2014-05-30T02:51:30';
$date = new DateTime($sunrise);
$date->add(new DateInterval('PT2H'));
echo $date->format('Y-m-d H:i:s');
// outputs: 2014-05-30 04:51:30
echo date('Y-m-d H:i:s', strtotime($sunrise . ' +2 hours'));
// outputs: 2014-05-30 04:51:30

Add minutes to datetime string

$datetime_from = '2013-08-27 14:17:00';
$datetime_till = date("Y-m-d H:i",strtotime("+45 minutes",$datetime_from));
The result is:
$datetime_till = '1970-01-01 01:00:00'
The expected result is
$datetime_till = '2013-08-27 15:02'
How to get it?
It will be like
$datetime_from = strtotime('2013-08-27 14:17:00');
$datetime_till = date("Y-m-d H:i",strtotime("+45 minutes",$datetime_from));
You need to convert $datetime_from to time
Orelse you can also try like(Iam not sure)
$dateTime = DateTime::createFromFormat('m/d/Y h:i', $datetime_from);
$datetime_from = $dateTime->format('U');
$datetime_till = date("Y-m-d H:i",strtotime("+45 minutes",$datetime_from));
Try-
$datetime_till = date("Y-m-d H:i",strtotime("+45 minutes",strtotime($datetime_from)));
You should use the DateTime class instead of old functional php.
$dateFrom = new \DateTime('2013-08-27 14:17:00');
$dateTill = new \DateTime('2013-08-27 14:17:00');
$dateTill->modify('+45 minutes');
// test if the dates are correct
echo $dateFrom->format('Y-m-d H:i:s'). ' - '.$dateTill->format('Y-m-d H:i:s');
There are numerous other methods you can benefit from the DateTime class.
You can use the DateTime object to do this in procedural style PHP like this:
$datetime_from = date_create('2013-08-27 14:17:00'); // Create a date object from the start date
$datetime_till = date_add($datetime_from, date_interval_create_from_date_string('45 minutes')); // Add the interval to the starting time
echo date_format($datetime_till, 'Y-m-d H:i'); // Format the date how you want it to be output
Hope this helps.
Use:
$datetime_from = strtotime('2013-08-27 14:17:00');
$datetime_till = date("Y-m-d H:i",$datetime_from+(45*60));
Use DateTime class for date/time modifications :
$datetime_from = new DateTime('2013-08-27 14:17:00');
$datetime_till = clone $datetime_from;
$datetime_till->modify('+45 minutes');
echo
'From: ' . $datetime_from->format('Y-m-d H:i:s') . "\n".
'Till: ' . $datetime_till->format('Y-m-d H:i:s');
Output will be :
From: 2013-08-27 14:17:00
Till: 2013-08-27 15:02:00
Valid modify() formats are explained in Date and Time Formats.
Please note that various strtotime() examples are not correct in date/time difference calculation. The simplest example is difference between 2013-03-31 21:00 and 2013-03-30 21:00. Which for naked eye is exact 1 day difference, but if you do subtract this 2 dates, you will get 82800 seconds which is 0.95833333333333 days. This is because of the time change from winter to summer time. DateTime handles leap years and time-zones properly.

Add minutes to current time

I am trying to add minutes to current date but it returns strange results
date_default_timezone_set('Asia/Karachi');
$currentDate = date("m-d-Y H:i:s");
$currentDate_timestamp = strtotime($currentDate);
$endDate_months = strtotime("+10 minutes", $currentDate_timestamp);
$packageEndDate = date("m-d-Y H:i:s", $endDate_months);
echo " <br> " . $packageEndDate . " <br> ";
echo $currentDate;
I am getting Output
01-01-1970 05:50:00
07-19-2013 20:25:23
It should return
07-19-2013 20:35:23
07-19-2013 20:25:23
After this I need to query to database so date format should be same. Database column is of string type.
Your code is redundant. Why format a timestamp as a string, then convert that string back to a timestamp?
Try
$now = time();
$ten_minutes = $now + (10 * 60);
$startDate = date('m-d-Y H:i:s', $now);
$endDate = date('m-d-Y H:i:s', $ten_minutes);
instead.
Probably the minimalist way would be:
date_default_timezone_set('Asia/Baku');
$packageEndDate = date('Y-m-d H:i:s', strtotime('+10 minute'));
echo $packageEndDate;
Output (Current time in my city at the time of writing):
2017-07-20 12:45:17
Try this:
$now = time();
$tenMinFromNow = date("m-d-Y H:i:s", strtotime('+10 minutes', $time));
$tenMinsFromNow = (new \DateTime())->add(new \DateInterval('PT10M'));
Will leave you with a DateTime object representing a time 10 minutes in the future. Which will allow you to do something like:-
echo $tenMinsFromNow->format('d/m/Y H:i:s');
See it working
PHP version >= 5.4 I'm afraid, but you should be using at least that version by now anyway.
Pakistan, which is the localisation explicitly set, uses "DD-MM-YYYY" format dates so the problem occurs when you cast the date into a string of "MM-DD-YYYY". This American format of date is not parseable by the Pakistan localisation.
If you still want to keep the round-trip to a string and back, use DD-MM-YYYY or the ISO datetime format.
While this is the only (current) answer which actually explains your original issue, I recommend the code be refactored as others have demonstrated.

Categories