convert between timestamp and date time - php

I tried this code,it will give me the right date but the time is not correct:
function convert_datetime($str) {
list($date, $time) = explode(' ', $str);
list($year, $month, $day) = explode('-', $date);
list($hour, $minute) = explode(':', $time);
$timestamp = mktime($hour, $minute, $year, $month, $day);
return $timestamp;
}
if(isset($_POST['submit']))
{
$datetime=$_POST['startdate'].' '.$_POST['start_hour'].":".$_POST['start_minute'];
$timestamp=convert_datetime($datetime);
echo "DateTime:".$datetime;
echo " ";
echo "Timestamp:".$timestamp;
echo " ";
$dateandtime = date("Y-m-d H:i", $timestamp);
echo "converted:".$dateandtime;
}
with input: 2013-1-21 21:51
I will get this out put
DateTime:2013-1-21 21:51 Timestamp:1358807073 converted:2013-01-21 22:24
so the order is not correct.and in the time part I have problem.How to fix this?

Use Datetime. It's much easier and more accurate:
$datetime = DateTime::createFromFormat("Y-m-d H:i", '2013-1-21 21:51');
echo 'Timestamp: ' . $datetime->getTimestamp() . PHP_EOL;
echo 'Datetime: ' . $datetime->format("Y-m-d H:i") . PHP_EOL;
Confirmed working

You are missing the seconds argument - see mktime on phpdocs. In your example seconds is being supplied the value 2013, which when added to the time alters the overall result.
function convert_datetime($str) {
list($date, $time) = explode(' ', $str);
list($year, $month, $day) = explode('-', $date);
list($hour, $minute) = explode(':', $time);
$timestamp = mktime($hour, $minute, 0, $year, $month, $day);
return $timestamp;
}
On a side note, php does have conversion functions built in. Try strtotime.

Put in a zero field for seconds when you are passing the time. I believe it is taking 2013 seconds and using it to add 2013/60 and using it to add 33 minutes to your time. I believe that mktime assumes current date for missing fields, which is why it is still getting 2013 for the year.

Related

Convert date (PHP) [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 4 years ago.
I am using JDF library for converting databases dates in my panel. My programming language is php and i am using while loop for show data. database date type is datetime.For example : 2018-07-21 11:14:19.678896
<?php
Include_once "jdf.php";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$array = explode(' ', $row['date']);
list($year, $month, $day) = explode('-', $array[0]);
list($hour, $minute, $second) = explode(':', $array[1]);
$timestamp = mktime($hour, $minute, $second, $month, $day, $year);
date_default_timezone_set("Asia/Tehran");
$converted_date = jdate("Y/m/d H:i:s", $timestamp);
echo $row['full_name'] . ", reg date:" . $converted_date;
}
When i run code, Y/m/d become convert BUT for H:i:s just first row become convert. I really dont know why ...
Can you help me ?
It's probably simpler to use the inbuilt DateTime class to process your data:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$date = date_create_from_format('Y-m-d H:i:s.u', $row['date'], new DateTimeZone('UTC'));
$date->setTimeZone(new DateTimeZone('Asia/Tehran'));
$converted_date = jdate('Y/m/d H:i:s', (int)$date->format('U'));
echo $row['full_name'] . ", reg date:" . $converted_date;
}
Output:
2018/07/21 15:44:19
Demo on 3v4l.org

PHP time function displays wrong value

I am using following code
list($date, $time) = explode(' ', $row['created_at']);
list($year, $month, $day) = explode('-', $date);
list($hour, $minute, $second) = explode(':', $time);
$timemodified = mktime($hour, $minute, $second, $month, $day, $year);
$threshold = time() - 6;
echo $threshold.'</br>';
echo $timemodified.'</br>';
echo $timemodified - $threshold;
It outputs
1428631618
1428643990
12372
The modified time is just two minutes ago. Why is the difference so big I am just subtracting six seconds. Am I missing sommething?
It's because the $threshold time is not really 6 seconds. You can use strtotime() function to subtract 6 seconds from your time
$newTime = strtotime('-6 seconds', $timemodified);
echo date('Y-m-d H:i:s', $newTime);
hope this helps. For my example see this: http://codepad.org/cRp858RG

PHP finding the expired time in seconds

Let say we have start date and end date
if (isset($_POST['start_date']))
$_POST['start_date'] = gmdate('Y-m-d H:i:s', strtotime($_POST['start_date']));
if (isset($_POST['end_date']))
$_POST['end_date'] = gmdate('Y-m-d H:i:s', strtotime($_POST['end_date']));
would $_POST['end_date'] - $_POST['start_date'] give you the expired time in seconds?
No, to get the expired time in seconds you would use strtotime():
$expired = strtotime($_POST['end_date'])-strtotime($_POST['start_date']);
if (isset($_POST['start_date']))
$_POST['start_date'] = gmdate('Y-m-d H:i:s', strtotime($_POST['start_date']));
if (isset($_POST['end_date']))
$_POST['end_date'] = gmdate('Y-m-d H:i:s', strtotime($_POST['end_date']));
if (isset($_POST['start_date']) && isset($_POST['end_date'])) echo 'Expired time in seconds: ' . $expired;
I suggest you to use mktime function to get the unix timestamp from a date literal, which is in milliseconds.
$startDate = mktime($hour, $minute, $second, $month, $day, $year);
$endDate = mktime($hour, $minute, $second, $month, $day, $year);
$diffInSeconds = ($endDate - $startDate) / 1000; // 1 second = 1000 miliseconds

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');
?>

PHP - Replace split [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 11 months ago.
I have these 2 functions in which I have to replace split with another php command:
function date_fr_mysql($date) {
list($jour,$mois,$annee)=split("/",$date);
$date = $annee."-".$mois."-".$jour;
return $date;
}
function date_mysql_fr($date) {
list($annee,$mois,$jour)=split("-",$date);
$date = $jour."/".$mois."/".$annee;
return $date;
}
with which function I can replace it to get the same result?
You can use the explode function.
The function explode is similar to split, except it does not regexes. Use preg_split if you need regex support.
I have this example from PHP manual on split function over date:
<?php
// Delimiters may be slash, dot, or hyphen `
$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year";
?>
After some experimentation, the solution to avoid a deprecated warning and still have the same result is:
<?php
// Delimiters may be slash, dot, or hyphen
// test preg_split per /
$valore2 = "2010/01/01";
//list($month, $day, $year) = split('[/.-]', $valore2);
list($year, $month, $day) = preg_split('[/|\.|-]', $valore2);
echo "Month: $month; Day: $day; Year: $year\n";
// test preg_split per -
$valore2 = "2010-01-01";
//list($month, $day, $year) = split('[/.-]', $valore2);
list($year, $month, $day) = preg_split('[/|\.|-]', $valore2);
echo "Month: $month; Day: $day; Year: $year\n";
// test preg_split per .
$valore2 = "2010.01.01";
//list($month, $day, $year) = split('[/.-]', $valore2);
list($year, $month, $day) = preg_split('[/|\.|-]', $valore2);
echo "Month: $month; Day: $day; Year: $year\n";
?>
Hope this helps.
Given it seems you're just changing - to /, how about
$date = str_replace('-', '/', $date);
date ( 'Y-m-d', strtotime ( $your_date ) );

Categories