Convert date (PHP) [duplicate] - php

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

Related

PHP: Date Formatting - MM/DD/YY > YYYY/MM/DD [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 8 years ago.
Hi I am trying to get some PHP date formatting resolved. The problem I am having is random unexpected results being returned instead of the correct date after I try and format them.
I have the date MM/DD/YY passed in as a string and I am wondering how to convert that to a YYYY/MM/DD. When it try to convert the date it is like it is staying in the same place but trying to convert the individual section so the MM (12) goes to the year YYYY (2012)
Here is the section of code I have been using to try and change the format:
$date = $_GET["datepicker"];
$arr[$i] = strftime("%Y-%m-%d", strtotime($date));
The $arr[$i] is just the array I am putting it into this shouldn't affect anything.
I have also tried the following:
$arr[$i] = date("Y-m-d", strtotime($date));
Thanks,
Kieran
The easiest way to get the output you need is to use the DateTime class, in particular: DateTime::createFromFormat:
$date = DateTime::createFromFormat('m/j/y', $_GET['datepicker']);
//now to get the outpu:
$arr[$i] = $date->format('Y-m-d');
There is a procedural-style alternative, too:
$date = date_create_from_format('m/j/y', $_GET['datepicker']);
//note, date_create_from_format returns an instance of DateTime
$arr[$i] = date_format($date, 'Y-m-d');//same as $date->format('Y-m-d');
You can use mktime:
$date = $_GET["datepicker"];
list($month, $day, $year) = explode('/', $date);
$timestamp = mktime(0, 0, 0, $month, $day, $year);
$output = date('Y-m-d', $timestamp)

Format date using php [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 8 years ago.
I have a PHP variable '$date', and it's value is: y/m/d h:i:s format.
e.g: $date = "2014-11-10 17:25:00";
I want to change this format to m/d/y h:i:s format, so that I'm using PHP code below. It's working fine but is there any PHP function to do it in one line of code ?
$date = "2014-11-10 17:25:00";
$explode = explode(" ", $date);
$part1 = $explode[0];
$part2 = $explode[1];
$explode = explode("-", $part1);
$year = $explode[0];
$month = $explode[1];
$day = $explode[2];
$created_date = "$month-$day-$year $part2";
You can use date() & strtotime() functions. Example:
$date = "2014-11-10 17:25:00";
echo date('m-d-Y H:i:s', strtotime($date));
Output:
11-10-2014 17:25:00

php function to add number of days to a date [duplicate]

This question already has answers here:
Adding days to $Date in PHP
(12 answers)
Closed 8 years ago.
I have found several posts regarding this topic but I cannot get my function to work.
If the amount of days to add > 0, the returning date = 70-01-01
Example:
$date='12-07-11'
$days='5'
Should return 17-07-11 instead of 70-01-01
I need to use the variables because $date and $days are results from an oracle query.
function addDayswithdate($date,$days)
{
$originalDate = $date;
$newDate = date("y-m-d", strtotime($originalDate));
if ($days>0)
{
$var="+". $days ." days";
$date = strtotime($var, strtotime($newDate));
}
$originalDate = $date;
$newDate = date("y-m-d", strtotime($date));
return $newDate;
}
Use Datetime::createFromFormat and DateInterval
$date = DateTime::createFromFormat('d-m-y','12-07-11');
$date->add(new DateInterval('P5D'));
echo $date->format('d-m-Y') . "\n";
Why not keep it simpler?
function addDays($date, $days)
{
$time = strtotime($date);
$new_time = $time + (86400 * $days) //86400 seconds per day
return $new_time;
}
function addDays($date, $days)
{
$date_uts = strtotoime($date);
$add_days = $days*86400;
$final_date = date('Y-m-d', $date_uts+$add_days);
return $final_date;
}
Why not do it like this:
echo date('Y-m-d', strtotime($date + $days .'days'));
In addition of using vanilla php DateTime class, you can use Carbon if you have to work often with dates.
Carbon let you do anything like this
$date = Carbon::now()->addDays(5);

convert between timestamp and date time

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.

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