need help converting time string to usable format - php

I have a string in the following format
yyyy-mm-dd-hh-mm-ss
The reason its in this format is because its part of a URL. I need help converting it to a usable time format in PHP.
Here is what I have tried so far.
$time = "2013-04-14-23-33-17";
$time2 = strtotime($time);
$time3 = date('M d, Y', $time2) . ' ' . _('at') . ' ' . date('h:i a', $time2);
echo $time3;
It just echos out Jan 01, 1970 at 12:00 am which is wrong instead of Apr 14, 2013 at 11:33 pm.

It doesn't work because that's not a valid date format. See Supported Date and Time Formats.
What you need to do is create a DateTime object by specifing a format for your string.
DateTime::createFromFormat does exactly that.

You could use DateTime to help you with the parsing:
$date = DateTime::createFromFormat('Y-m-d-H-i-s', $time);
echo $date->format('M d, Y h:i a');

Related

Converting date (with milliseconds) into timestamp

I have date format like '25 May 2016 10:45:53:567'.
I want to convert into the time stamp.
strtotime function returns empty.
$date = '25 May 2016 10:45:53:567';
echo strtotime($date);
// returns empty
When I removed the milliseconds, it's working.
$date = '25 May 2016 10:45:53';
echo strtotime($date);
// returns 1464153353
Please sort out my issue. Thanks in advance.
Use DateTime:
$date = DateTime::createFromFormat('d M Y H:i:s:u', '25 May 2016 10:45:53:000');
echo $date->getTimestamp();
// 1464165953
// With microseconds
echo $date->getTimestamp().'.'.$date->format('u');
// 1464165953.000000
Split string:
$date = '25 May 2016 10:45:53:001';
preg_match('/^(.+):(\d+)$/i', $date, $matches);
echo 'timestamp: ' . strtotime($matches[1]) . PHP_EOL;
echo 'milliseconds: ' . $matches[2] . PHP_EOL;
// timestamp: 1464162353
// milliseconds: 001
Use Datetime instead of date and strtotime.
//using date and strtotime
$date = '25 May 2016 10:45:53:000';
echo "Using date and strtotime: ".date("Y-m-d H:i:s.u", strtotime($date));
echo "\n";\
//using DateTime
$date = new DateTime();
$date->createFromFormat('d M Y H:i:s.u', '25 May 2016 10:45:53:000');
echo "Using DateTime: ".$date->format("Y-m-d H:i:s.u");
// since you want timestamp
echo $date->getTimestamp();
// Output
// Using date and strtotime: 1969-12-31 16:00:00.000000
// Using DateTime: 2016-05-28 03:25:22.000000
Example

How to convert string with date and time AM/PM to 24 Hour mysql timestamp format

I am trying to insert date and time into mysql datetime field from a string having following dd/mm/yyyy hh:mm:ss AM/PM format:
20/10/2014 05:39 PM
20/10/2014 05:39 AM
I know MYSQL timestamp format is yyyy-mm-dd hh:mm:ss or 0000-00-00:00:00:00
So if I do:
$s = substr("20/10/2014 05:39 PM", 0, 10);
$h = date("G:i", strtotime($s));
list($day, $month, $year, $hour, $minute) = split('[/ :]', "20/10/2014 05:39 PM");
echo $d1me = $year . '-' . $month. '-' . $day . ' ' . $h;
I get 2014-10-20 19:00
So I guess there is a problem with date_default_timezone_set() function, How to solve this and get expected result?
20/10/2014 05:39 PM -> 2014-10-20 17:39:00
20/10/2014 05:39 AM -> 2014-10-20 05:39:00
How to do it?
MySQL already knows how to parse many different types of date strings natively, using the STR_TO_DATE() function in combination with format strings used by DATE_FORMAT().
So, I would not involve PHP in this process at all, and instead allow MySQL to parse the input itself.
The format string you need to use is %d/%m/%Y %h:%i %p, where the %p represents AM/PM.
You can use the entire expression right in your INSERT statement, passing the strings directly from PHP assuming you have validated their format already.
INSERT INTO your_table (timestamp_column) VALUES (STR_TO_DATE('20/10/2014 05:39 PM', '%d/%m/%Y %h:%i %p'));
...will correctly insert the DATETIME value 2014-10-20 17:39:00 into your table.
If you really prefer to do it in PHP first, use DateTime::createFromFormat() (PHP 5.3+) using the format string 'd/m/Y H:i A'
$d = DateTime::createFromFormat('d/m/Y H:i A', '20/10/2014 05:39 PM');
var_dump($d);
class DateTime#2 (3) {
public $date =>
string(26) "2014-10-20 17:39:00.000000"
public $timezone_type =>
int(3)
public $timezone =>
string(15) "America/Chicago"
To get a MySQL formatted date back out of it,
echo $d->format('Y-m-d H:i:s');
// 2014-10-20 17:39:00
If you are in the deeply unfortunate situation of having a PHP version older than 5.3, you can achieve similar results with strptime() but you'll need to assemble its array output into MySQL's string format.
This should work for you:
<?php
$input = "20/10/2014 05:39 AM"; //20/10/2014 05:39 PM
list($day, $month, $year, $hour, $minute, $dayType) = preg_split('/[\/\s:]+/', $input);
echo $d1me = $year . '-' . $month. '-' . $day . ' ' . ($dayType == "PM"?$hour+12: $hour) . ":" . $minute . ":00";
?>
Output:
2014-10-20 05:39:00 //2014-10-20 17:39:00
I think you can use the following code. It's easier to understand:
echo date("Y-m-d H:i", strtotime("20/10/2014 05:39 PM"));
This is the better way if you are using php
echo date('Y-m-d H:i', strtotime('20/10/2014 05:39 PM'));
echo date("Y-m-d H:i:s", strtotime("20-10-2014 05:39 PM"));
Use above code - but keep in mind you have "-" in place of "/" in input date.

PHP strtotime() function off using "1-January-2013"

I am collecting a user's birthday from a registration form and am hoping to convert this to a timestamp using strtotime before storing it in a database, but this isn't going so well.
I have them select their date in 3 select boxes, one is for the day, another the month, and lastly the year, and then I feed those into strtotime. The problem is, I am inputting "1", "January", and "2013" for the variables previously listed and am feeding them into strtotime like this:
$user->birthday = strtotime($input['bday'].'-'.$input['bmonth'].'-'.$input['byear']);
This reads when echoed as "1-January-2013", yet the timestamp it spits out renders to "Dec 31, 2012" using:
date_default_timezone_set("America/Los_Angeles");
echo date("M d, Y", 1356998400);
I have been testing different methods profusely but cannot get this to work. I'd appreciate any assistance.
Are you setting date_default_timezone_set() before the call to strtotime() or after? Since the default timezone is UTC, and LA is UTC-08.00, that could account for the difference.
You have to call date_default_timezone_set before calling strtotime, so that you have the same timezones when parsing the input date and when you're displaying the date.
Not too sure how your code is failing, but this works for me:
// Set the test data.
$test_data = '1-January-2013';
// Get the Unix datetime from the test data.
$date = strtotime($test_data);
// Format the Unix datetime.
$dateFormat = date("M d, Y", $date);
// Output for debugging.
echo 'test_data: ' . $date . '<br />';
echo 'date: ' . $date . '<br />';
echo 'dateFormat: ' . $dateFormat . '<br />';
Output from my side using PHP 5.5 is:
test_data: 1357016400
date: 1357016400
dateFormat: Jan 01, 2013
But on the outside chance those - dashes are choking things, try this:
// Set the test data.
$test_data = '1-January-2013';
// Filter out dashes from the '$test_data'
$test_data = preg_replace('/-/', ' ', $test_data);
// Get the Unix datetime from the test data.
$date = strtotime($test_data);
// Format the Unix datetime.
$dateFormat = date("M d, Y", $date);
// Output for debugging.
echo 'test_data: ' . $date . '<br />';
echo 'date: ' . $date . '<br />';
echo 'dateFormat: ' . $dateFormat . '<br />';
And again, the output from my side using PHP 5.5 is:
test_data: 1357016400
date: 1357016400
dateFormat: Jan 01, 2013
It's definitely a time zone issue. 1356998400 is 01 / 01 / 13 # 12:00:00am UTC, so when you do this:
date_default_timezone_set("America/Los_Angeles");
echo date("M d, Y", 1356998400);
The Unix time 1356998400 is Dec 31, 2012 in Los Angeles! I suspect you're getting your timestamp in UTC and then outputting it with PST.

Converting string to time in PHP

I am having some trouble trying to convert string to time.
My Code is:
$time = strtotime("14 November, 2013 2:30 AM");
echo $time ."<br />";
echo date("m/d/Y", $time);
I know that strtotime is not magic, and I checked out the acceptable date/time formats but I am not sure how to convert the string to another string without converting it to time first.
What's the easiest way to accomplish this?
Take a look at DateTime::createFromFormat and then call format on the created DateTime instance.
Something like:
$yourTimeString = '14 November, 2013 2:30 AM';
$date = DateTime::createFromFormat('d F, Y h:i A', $yourTimeString);
echo $date->format('m/d/Y');
One way is to rewrite the string using explode and list.
<?php
// here we assume "day month, year time AMPM"
$date = "14 November, 2013 2:30 AM";
// assign a variable to each part of the string
list($day,$month,$year,$time,$ampm) = explode(" ",$date);
// remove the commas at the end of the month
$month = str_replace(',','',$month);
// Now we rewrite the strtotime string
$time = strtotime($month . " " . $day . ", " . $year . " " . $time . " " . $ampm);
echo $time ."<br />";
echo date("m/d/Y", $time);
Php date() function allow natural language string for parsing date,
for Ex:
echo date("d-M-Y", strtotime("first monday of 2019-07")); // returns first monday of july 2019
echo date("d-M-Y", strtotime("last sat of July 2008"));
You can find here php instructions to parsing date as natural languages.
http://php.net/manual/en/datetime.formats.relative.php

How to get AM/PM from a datetime in PHP [duplicate]

This question already has answers here:
Convert from MySQL datetime to another format with PHP
(18 answers)
Closed 2 years ago.
I have a date time in a variable. My format is 08/04/2010 22:15:00. I want to display this like 10.15 PM. How to do this in PHP?
You need to convert it to a UNIX timestamp (using strtotime) and then back into the format you require using the date function.
For example:
$currentDateTime = '08/04/2010 22:15:00';
$newDateTime = date('h:i A', strtotime($currentDateTime));
$dateString = '08/04/2010 22:15:00';
$dateObject = new DateTime($dateString);
echo $dateObject->format('h:i A');
Use strtotime() to make the date a UNIX timestamp.
For output, check out the various options of date().
$timestamp = strtotime("08/04/2010 22:15:00");
date("h.i A", $timestamp);
<?php
$dateTime = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
echo $dateTime->format("d/m/y H:i A");
?>
You can use this to display the date like this
22/06/15 10:46 AM
Like this:
$date = '08/04/2010 22:15:00';
echo date('h:i A', strtotime($date));
Result:
10:15 PM
More Info:
date
strtotime
for flexibility with different formats, use:
$dt = DateTime::createFromFormat('m/d/Y H:i:s', '08/04/2010 22:15:00');
echo $dt->format('g:i A')
Check the php manual for additional format options.
PHP Code:
date_default_timezone_set('Asia/Kolkata');
$currentDateTime=date('m/d/Y H:i:s');
$newDateTime = date('h:i A', strtotime($currentDateTime));
echo $newDateTime;
Output: 05:03 PM
$currentDateTime = $row['date'];
echo $newDateTime = date('l jS \of F Y h:i:s A', strtotime($currentDateTime));
Perfect answer for AM/PM live time solution
<?php echo date('h:i A', time())?>
Just simply right A
{{ date('h:i A', strtotime($varname->created_at))}}
For (PHP >= 5.2.0):
You can use DateTime class. However you might need to change your date format. Didn't try yours.
The following date format will work for sure: YYYY-MM-DD HH-MM-SS
$date = new DateTime("2010-04-08 22:15:00");
echo $date->format("g"). '.' .$date->format("i"). ' ' .$date->format("A");
//output
//10.15 PM
However, in my opinion, using . as a separator for 10.15 is not recommended because your users might be confused either this is a decimal number or time format. The most common way is to use 10:15 PM
It is quite easy. Assuming you have a field(dateposted) with the type "timestamp" in your database table already queried and you want to display it, have it formated and also have the AM/PM, all you need do is shown below.
<?php
echo date("F j, Y h:m:s A" ,strtotime($row_rshearing['dateposted']));
?>
Note: Your OUTPUT should look some what like this depending on the date posted
May 21, 2014 03:05:27 PM

Categories