date_parse_from_format to unix timestamp - php

I have a question regarding the date_parse_from_format() method:
$parsed = date_parse_from_format("Y d M H:i T", '2012 28 Nov 21:00 CET');
Returns associative array with detailed info about given date.
This will return an array with some date info. But is there any way to convert it to a unix timestamp?

Johan,
Heres an exact example of how to implement mktime into your scenario:
$parsed = date_parse_from_format("Y d M H:i T", '2012 28 Nov 21:00 CET');
$new = mktime(
$parsed['hour'],
$parsed['minute'],
$parsed['second'],
$parsed['month'],
$parsed['day'],
$parsed['year']
);
echo $new; //returns: 1354136400
For future reference, you can use var_dump() or print_r() on an array to see how to access the nested values.
var_dump of $parsed
array (size=16)
'year' => int 2012
'month' => int 11
'day' => int 28
'hour' => int 21
'minute' => int 0
'second' => int 0
'fraction' => boolean false
'warning_count' => int 0
'warnings' =>
array (size=0)
empty
'error_count' => int 0
'errors' =>
array (size=0)
empty
'is_localtime' => boolean true
'zone_type' => int 2
'zone' => int -60
'is_dst' => boolean false
'tz_abbr' => string 'CET' (length=3)

You can get the UNIX time-stamp by trying to use mktime() for a date.
For Example:
echo mktime(12, 20, 0, 10, 4, 2012 );
You will get the output like that 1349353200
And if you want AM/PM just add 12 to hours if PM.
For Example:
mktime($isAM ? $hrs : ($hrs + 12), $mins, $secs, $m, $d, $y);
and you can also use strtotime():
strtotime() - Parse about any English textual datetime description into a Unix timestamp
echo strtotime("2012-11-03 11:24:00PM");
You will get the output like that 1351985040

In PHP >=5.3, you can use the DateTime constructor which functions exactly like date_parse_from_format. Bonus points: it's a one-liner.
For instance, to convert a date in a UK format to a UNIX timestamp, we can do:
DateTime::createFromFormat("d/m/Y, H:i", '27/03/2020, 22:00')->getTimestamp()
-> int(1585346400)

mktime() should suit your needs perfectly :) Check out http://php.net/manual/en/function.mktime.php to see how you can use it!

Related

PHP DateTime::createFromFormat return wrong date

I've got a date like : $date = DateTime::createFromFormat('D d/m', 'Mon 05/02'); but instead of 05 february the datetime returned is DateTime Object ( [date] => 2021-02-08 10:02:10.000000 [timezone_type] => 3 [timezone] => Europe/Brussels )
Answer
Corrected with the Y input and got the right result, php was using 2021 when i was constructing 2022 year
If the (wrong) day of the week is to be ignored, then an * only needs to be set in the format instead of the "D".
$date = DateTime::createFromFormat('* d/m', 'Mon 05/02');
"Mon" is ignored and the expression "05/02" is used to determine the date.
DateTime::__set_state(array(
'date' => "2021-02-05 18:28:31.000000",
'timezone_type' => 3,
'timezone' => "Europe/Berlin",
))
Because in 2021, February 5 is Friday, and February 8 is Monday.

Represent a string of digits as days of the week

I have a 7 digit string of individual boolean values (e.g. 0010010), each digit representing a day of the week, Sunday to Saturday. If the day is active it's flagged as 1.
I want to check the string and output the abbreviated name of any days that are active.
Examples
1000000 is converted to Sun because the digit for Sunday is active.
0100010 is converted to MonFri
1111111 is converted to SunMonTueWedThuFriSatSun
I am using a system someone else designed here. What is the simplest method to achieve this with PHP?
I'll post this here, hoping that it may improve the question:
<?php
$dow =['mon','tue','wed','thu','fri','sat','sun'];
$day = '0010000';
$result = array_combine($dow, str_split($day));
var_export($result);
Output:
array (
'mon' => '0',
'tue' => '0',
'wed' => '1',
'thu' => '0',
'fri' => '0',
'sat' => '0',
'sun' => '0',
)
Further with the additional information:
$day = '1000100';
$result = array_combine($dow, str_split($day));
print implode(array_keys(array_filter($result)));
Output:
monfri

PHP's date functions: converting from weeknumber back to month

Given the information below:
Year: 2012
Weeknumber: 4
Dayname: TUE
How can i convert this to a valid date like 2012-01-12 (YYYY-MM-DD) using PHP's date functions?
Thanx
The DateTime class can't do this, but the function strptime can.
$d = strptime('TUE 4 2012', '%a %W %Y');
var_dump($d);
That returns an array:
array
'tm_sec' => int 0
'tm_min' => int 0
'tm_hour' => int 0
'tm_mday' => int 24
'tm_mon' => int 0
'tm_year' => int 112
'tm_wday' => int 2
'tm_yday' => int 23
'unparsed' => string '' (length=0)
Note that tm_year contains the number of years since 1900 and tm_month is 0-based, not 1-based. So this does represent 2012-01-24, which is correct.
Use this function:
function get_date($year,$week,$day,$start_sunday=false){
$day_array = array('Mon'=>1,'Tue'=>2,'Wed'=>3,'Thu'=>4,'Fri'=>5,'Sat'=>6,'Sun'=>($start_sunday?0:7));
$month_array = array(31,($year%4==0?29:28),31,30,31,30,31,31,30,31,30,31);
$week *= 7;
$month = 1;
for($i=0;$i<count($month_array);$i++){
if($week-$month_array[$i]<=0){
break;
}
$week -= $month_array[$i];
$month++;
}
$format = "$year $month $week";
$date = date_create_from_format("Y m j",$format);
$date_num = date_format($date,"D");
$curr = $day_array[ucfirst(strtolower($day))]-$day_array[$date_num];
$got_date = strtotime("$curr ".($curr==1||$curr==-1?"day":"days"),strtotime(date_format($date,"Y-m-j")));
return $got_date;
}
where $start_sunday should be true if week starts from sunday
$year is the year
$week is week number
$day is short weekday name i.e.mon,tue,wed,....
this function will get you a date form the given format.
Enjoy............

Calculate number of days between two given dates

Can anyone correct the error in my script to calculate the number of days between 2 dates.
The dates have been input through a form, the variable info is as followed:
[departon] => Array ( [0] => 1 [1] => June [2] => 2011 )
[returnon] => Array ( [0] => 31 [1] => June [2] => 2011 )
I have written the code to calculate these dates, but its not calculating the day, it just outputs 0.
<?php
$first_date = mktime(12, 0, 0, $_POST['departon'][1], $_POST['departon'][0], $_POST['departon'][2]);
$second_date = mktime(12, 0, 0, $_POST['returnon'][1], $_POST['returnon'][0], $_POST['returnon'][2]);
$days = $second_date-$first_date;
echo floor($days/60/60/24) . " days";
?>
Help would be much appreciated.
The easiest way is by using datetimes.
Consider this:
var_dump(new DateTime('1 July 2007'));
$a = new DateTime('1 July 2007');
$b = new DateTime('1 June 2001');
var_dump($a->diff($b));
The var_dump will allow you to see the different kind of time you can extract from it.
object(DateInterval)[3]
public 'y' => int 6
public 'm' => int 1
public 'd' => int 0
public 'h' => int 0
public 'i' => int 0
public 's' => int 0
public 'invert' => int 1
public 'days' => int 2221
You can convert your array to a date time very easily by using
$date = new DateTime(join(" ",$array));
$date2 = new DateTime(join(" ",$array2));
$diff = $date->diff($date2);
Here's an easy way:
$depart = strtotime(implode(' ', $_POST['departon']));
$return = strtotime(implode(' ', $_POST['returnon']));
$diff = floor(($return - $depart) / (60 * 60 * 24));
Note: there's only 30 days in June.
The mktime documentation specifies a number for the month, so you'd need to convert 'June' to '6'.

break apart formatted date into individual month/day/year hour/minute/second in php

I have a date in the following format
November 18, 2009, 3:00PM
How can i break that up so that i can store each value as its own variable?
such as...
$month //November
$day //18
$year //2009
$hour //03
$minute //00
$ampm //PM
Use the 'date_parse' (http://nl2.php.net/manual/en/function.date-parse.php) function. It returns an array with the parsed items:
Array
(
[year] => 2006
[month] => 12
[day] => 12
[hour] => 10
[minute] => 0
[second] => 0
[fraction] => 0.5
[warning_count] => 0
[warnings] => Array()
[error_count] => 0
[errors] => Array()
[is_localtime] =>
)
Convert your date into a timestamp, then with the timestamp you can easily get your parts. An other way is using a regular expression.
$str = "November 18, 2009, 3:00PM";
list($month,$day,$year,$time) = preg_split('/[ ,]/',$str,false,PREG_SPLIT_NO_EMPTY);
preg_match('/([0-9]+):([0-9]+)([AP]M)/',$time,$timeparts);
list($time,$hour,$minute,$ampm) = $timeparts;
echo "\$month $month\n";
echo "\$day $day\n";
echo "\$year $year\n";
echo "\$hour $hour\n";
echo "\$minute $minute\n";
echo "\$ampm $ampm\n";
Output
$month November
$day 18
$year 2009
$hour 3
$minute 00
$ampm PM
More complex solution.
If your dates may be in the different standards you can use date() function (http://php.net/manual/en/function.date.php) + strtotime() function (http://php.net/manual/en/function.strtotime.php), which parse string and returns the unix timestamp.
For example, if you want to get a year from your date string you could write next code:
$date = 'November 18, 2009, 3:00PM';
$year = date('Y', strtotime($date));
Or, if you want to know how much days in the month in date you get, you could write such code:
$date = 'November 18, 2009, 3:00PM';
$num_of_days = date('t', strtotime($date));
't' returns the number of days in the given month.

Categories