This is something that I've mostly finished and I'm wondering if there's a way to clean up the code and to get to function correctly.
I have a table with the date and time a user joined (YYYY-MM-DD HH:MM:SS). I was wanting to split up the various values so I used both the list explode functions, but was only able to split one group of values:
$joined = $row ["joined"]; // <- "2008-06-03 15:01:08"
list ($year, $month, $day) = explode ("-", $joined);
list ($hour, $minute, $second) = explode (":", $joined);
list ($seperation) = explode (" ", $joined);
echo $joined . "<br>\n";
echo $year . "<br>\n";
echo $month . "<br>\n";
echo $day . "<br>\n";
echo $hour . "<br>\n";
echo $minute . "<br>\n";
echo $second . "<br>\n";
The following was the output:
2008-06-03 15:01:08 ($joined)
2008 ($year)
06 ($month)
03 15:01:08 ($day)
2008-06-03 15 ($hour)
01 ($minute)
08 ($second)
I'm wanting to know how I can explode the 3 characters (the dash, colon and space) to be able to use the variables correctly and have it look like the following:
2008-06-03 15:01:08 ($joined)
2008 ($year)
06 ($month)
03 ($day)
15 ($hour)
01 ($minute)
08 ($second)
Try the following:
$year = date("Y", strtotime($joined));
$month = date("m", strtotime($joined));
$day = date("d", strtotime($joined));
$hour = date("H", strtotime($joined));
$minute = date("i", strtotime($joined));
$second = date("s", strtotime($joined));
Or a better solution:
$date = getdate(strtotime($joined));
When dealing with dates it is best to use date parsing instead of explode, or regex. The above uses strtotime() to convert the date string into Unix timestamp and then outputs them based on the date patterns.
And the second solution is much better as it returns an associative array of time fields.
But if you really do want to use list() and explode, here is a solution.
list($date, $time) = explode(" ", $joined);
list ($year, $month, $day) = explode ("-", $date);
list ($hour, $minute, $second) = explode (":", $time);
It separates date and time first, and then uses explode on them separately.
Related
I am getting a date from the mysql database:
here is what it comes out as:
2017-01-20
what would be the fastest way to get the month, day, and year, so for example, when i echo, it will be like this:
echo $month; //01
echo $day; //20
echo $year; //2017
Well, if you know that the output will consistently be a string in the format "YYYY-MM-DD", the most basic approach is:
<?php
$query = ... //query is your string "YYYY-MM-DD"
$year = substr($query, 0, 4);
$month = substr($query, 5, 2);
$day = substr($query, 8, 2);
echo $month;
echo $day;
echo $year;
?>
Let's assume you have that string in a variable called $date
$date = '2017-01-20';
You can explode it into a list if you are sure the format is consistent:
list($year, $month, $day) = explode("-", $date, 3);
You could convert the date to a time integer using strtotime to use in other functions like date. This has the added benefit of being able to test that this is a well-formed date:
$time = strtotime($date);
if ($time === false) die("Bad date format: $date.");
$year = date('Y', $time);
$month = date('m', $time); // 'n' if you don't want leading zero
$day = date('d', $time); // 'j' if you don't want leading zero
As jasonmoqio points out, since you asked for fastest, substr is a tiny bit faster than exploding. (On my workstation looping substr vs. explode 10 million times only produced an improvement of 1/1000th of a second over exploding, so unless this is in a loop that gets run millions of times, you will not notice the difference and should opt for code readability.)
$year = substr($date, 0, 4);
$month = substr($date, 5, 2);
$day = substr($date, 8, 2);
Try this:
$date = new DateTime('2017-01-20');
echo 'Year:'.$date->format("Y");
echo 'Month:'.$date->format("m");
echo 'Day:'.$date->format("d");
Output:
Year: 2017
Month: 01
Day: 20
If you want to quickly get the date from mysql, try using regex like this.
if (preg_match('/^(?P<year>\d+)[-\/](?P<month>\d+)[-\/](?P<day>\d+)$/', $your_date, $matches)) {
$mydate = $matches['year'] . "-" . $matches['month'] . "-" . $matches['day'];
$whatever = date('Y-m-d', strtotime($tgl));
// You can echo it...
// echo $matches['year'];
// echo $matches['month'];
// echo $matches['day'];
}
Hope this help you out. :D
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.
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
I usually mess this up, but I am trying to get a year from a variable $date = 2011-01-01 I am trying to get 2011 from the variable...I tried this but it didnt echo anything out...
date(strtotime("Y"), strtotime($date));
$year = date('Y', strtotime('2011-01-01'));
Or, if you don't want to convert to date, and trust your input format:
$year = explode('-', '2011-01-01')[0];
The above requires PHP 5.4, on older versions you need two lines:
$arr = explode('-', '2011-01-01');
$year = $arr[0];
Or yet, this slightly faster alternative suggested by tigrang:
$year = substr($date, 0, 4);
Or, an even faster way, as salathe suggested:
$year = (int) $date;
(everything after the first dash will be ignored, so $year will contain an integer with the year part of the date (unlike the other options, where $year would be a string).
date('Y', strtotime($date)) should do
First arg is the format, second is timestamp.
You can explode the date into a list and call each date item individually.
$date = '2012-01-01';
list($year, $month, $day) = explode('-', $date);
echo $year; // echoes 2012
May I suggest using PHP's DateTime class as an alternative:
$date = '2011-01-01';
$dateTime = new DateTime($date);
echo $dateTime->format('Y');
DateTime is all well and good, but lets go old school.
sscanf($date, '%d', $year);
// or
$year = strtok($date, '-');
// or
$year = substr($date, 0, 4);
// or
$year = (int) $date;
or, putting the sensible hat back on, you could use DateTime or correctly use date().
$datetime = new DateTime($date);
$year = $datetime->format('Y');
// or
$year = date('Y', strtotime($date));
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 ) );