PHP - Replace split [duplicate] - php

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

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

how to use preg_split() instead of split ()

newbee here...
I'm trying to replace the split() functions in a website so I found preg_split() to use. First had to find out how the split() function works so I looked at this example at the php.net site:
<?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<br />\n";
?>
The output was as expected:
Month: 04; Day: 30; Year: 1973
So I thought it would be easy and just change it to:
<?php
// Delimiters may be slash, dot, or hyphen
$date = "04-30/1973";
list($month, $day, $year) = preg_split('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year<br />\n";
?>
Output:
Month: 04-30/1973; Day: ; Year:
What is wrong in my thinking?
Just add some symbols to define start/end of regular expression. It can be ~, for example:
$date = "04-30/1973";
list($month, $day, $year) = preg_split('~[/.-]~', $date);
echo "Month: $month; Day: $day; Year: $year<br />\n";
Update:
If your code works with / as regexp borders, then you have to escape / with a backslash:
list($month, $day, $year) = preg_split('/[\/.-]/', $date);

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.

Retrieve date, month, year from a date in php

I have this piece of code which gets me a field from the database:
$end_date=$row1['end_date'];
If i print it it gives me something like: 25-09-2012
What i need is to get the month value, the year and date.
something like:
$month=09;
$day=25;
$year=2012;
How can i do that?
thanks!
Using DateTime:
$date = new DateTime($row1['end_date']);
$year = $date -> format('Y');
$month = $date -> format('m');
$day = $date -> format('d');
If your timestamps are all like the one provided, keep it simple:
list($day, $month, $year) = explode('-', $row1['end_date']);
In your case, you can use the explode function like this :
// store a string containing "25-09-2012"
$end_date = $row1['end_date'];
// split "25-09-2012" into an array of three elements
$thedate = explode("-", $end_date);
// retrieve the values
$month = $thedate[0]; // 25
$day = $thedate[1]; // 09
$year = $thedate[2]; // 2012
try
[month('end_date')]
[day('end_date')]
[year('end_date')]
Or use explode and use - as the delimiter
Take a peak at this helpful tutorial describing various formatting methods and useful date functions in PHP:
Date/Time Functions
Date Formats
A. You can use DateTime
$date = DateTime::createFromFormat('d-m-Y',$row1['end_date']);
$month = $date->format("m");
$day = $date->format("d");
$year = $date->format("Y");
B. Using strtotime
$date = strtotime($row1['end_date']);
$month = date("m", $date);
$day = date("d", $date);
$year = date("Y", $date);
C. You can just sscanf scan through the string
$date = sscanf($row1['end_date'], "%d-%d-%d");
$month = $date[0] ;
$day = $date[1] ;
$year = $date[2] ;
D. Another method is using list & explode
list($day, $month, $year) = explode('-', $row1['end_date']);
Do it on a single line and format it however you would like. (Dec, December, 12) and so on with date().
list($month, $day, $year) = explode('-', date('m-d-Y', strtotime($row1['end_date'])));
$values = getdate(strtotime($row1['end_date']));
echo $values['mon']; //month
echo $values['mday']; //day
echo $values['year']; //year

PHP split string into parts

I have string with following format:
$date = "2012-07-22 17:48:24";
I want to get the year, month and date in the variables and ignore the time. I am trying following:
list($year, $month, $day) = split('[-]', $date);
This returns correct values to $year and $month, but the $day gets: "22 17:48:24", while I want to get only 22.
Instead of exploding the value you could use a DateTime object:
<?php
$date = "2012-07-22 17:48:24";
$dateTime = new DateTime($date);
var_dump(array(
'year' => $dateTime->format('Y'),
'month' => $dateTime->format('m'),
'day' => $dateTime->format('d'),
));
This would be the most flexible option imho.
As #zerkms noted in his comment you could also use strtotime() and date(), but I find myself only using the DateTime class lately. Not only because it has a nice OO API, but also because it will keep on working after the year 2038 :-). The comment is not wrong though.
There's also the sscanf() function.
sscanf('2012-07-22 17:48:24', '%d-%d-%d', $year, $month, $day);
Use explode:
$date = "2012-07-22 17:48:24";
$date = explode(" ", $date);
list($year, $month, $day) = split('[-]', $date[0]);
EDIT:
You should use explode for the date too:
list($year, $month, $day) = explode('-', $date[0]);
The use of split is discouraged as it was deprecated.
$date = "2012-07-22 17:48:24";
preg_match('~^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$~', $date, $m);
print_r($m);
$date = date('Y-m-d', strtoime("2012-07-22 17:48:24"));
list($year, $month, $day) = split('[-]', $date);

Categories