I'm trying to convert the string 11/24/2011 # 01:15pm to a UNIX timestamp. The format is m-d-Y # h:ia
I can't seem to get strtotime to work with the string. Is there a way to reverse the data function? Is my only choice to create a new non-default php function to convert the string?
The server is running CentOS 5, Apache 2.2 and PHP 5.2.17.
Use the more modern DateTime class (so long as you're using >= 5.3).
$unix = DateTime::createFromFormat('m/d/Y # h:ia', '11/24/2011 # 01:15pm')
->getTimestamp();
CodePad.
Under PHP 5.2, you can use strptime to parse a date-time string with a specific format, then use mktime to convert the result to a timestamp.
$timeString = '11/24/2011 # 01:15pm';
$timeArray = strptime($timeString, '%m/%d/%Y # %I:%M%p');
$timestamp = mktime(
$timeArray['tm_hour'], $timeArray['tm_min'], $timeArray['tm_sec'],
$timeArray['tm_mon']+1, $timeArray['tm_mday'], $timeArray['tm_year']+1900
);
This should be abstracted as a function, possibly two:
function strptimestamp($date, $fmt) {
$timeArray = strptime($date, $fmt);
return mktime(
$timeArray['tm_hour'], $timeArray['tm_min'], $timeArray['tm_sec'],
$timeArray['tm_mon']+1, $timeArray['tm_mday'], $timeArray['tm_year']+1900
);
}
function strpmy($date) {
return strptimestamp($date, '%m/%d/%Y # %I:%M%p');
}
Support for parsing the period abbreviation appears to vary from OS to OS. If the above doesn't work on a particular OS, try "%P" instead of "%p" or pass the time string through strtoupper (or both). The following should work under any OS, though it's preferable to get strptime to handle the entirety of the parsing, as the following is less suitable as the basis for a generic strptimestamp function.
static $pm_abbrevs = array('pm' => 1, 'p.m.' => 1, 'µµ' => 1, 'µ.µ.' => 1);
$timeString = '11/24/2011 # 01:15pm';
$timeArray = strptime($timeString, '%m/%d/%Y # %I:%M');
$period = strtolower($timeArray['unparsed']);
if (isset($pm_abbrevs[$period])) {
$timeArray['tm_hour'] += 12;
}
$timestamp = mktime(
$timeArray['tm_hour'], $timeArray['tm_min'], $timeArray['tm_sec'],
$timeArray['tm_mon']+1, $timeArray['tm_mday'], $timeArray['tm_year']+1900
);
If you replace the ' # ' with a space, then strtotime should be able to understand it natively.
<?php
$x = "11/24/2011 # 01:15pm";
$x = str_replace(" # ", " ", $x);
$y = strtotime($x);
$z = date("m-d-Y # h:ia", $y);
echo "x: $x<br />\n";
echo "y: $y<br />\n";
echo "z: $z<br />\n";
?>
Output:
x: 11/24/2011 01:15pm
y: 1322140500
z: 11-24-2011 # 01:15pm
Case sensitivity may be your issue http://php.net/manual/en/datetime.formats.php.
Perhaps run $x through strtoupper() first then str_replace('#', '', $x) (notice it's replacing # with an empty string), then try strtotime(). Hope this helps.
$search = array('/',',','#');
$replace = array('-','','');
echo strtotime( str_replace($search,$replace,'16/7/2013 # 7:30AM') );
this will replace the parts of the string in the time string you are trying to convert into a format that is acceptable to strtotime. You can always add more string parts you want to replace to the arrays.
Also you dont need to have latest php for this.
Output:
1373952600
Related
I echo this :
php> echo date("Y-m-d\TH:i:s");
2011-05-27T11:21:23
How can do with date function to get this date format:
2011-01-12T14:41:35.7042252+01:00 (for example)
35.7042252 => seconds.decimal-fraction-of-second
I have tried:
php> function getTimestamp()
... {
... return date("Y-m-d\TH:i:s") . substr((string)microtime(), 1, 8);
... }
php> echo getTimestamp();
2011-05-27T15:34:35.6688370 // missing +01:00 how can I do?
date('Y-m-d\TH:i:s.uP')
u for microseconds was added in PHP 5.2.2. For earlier or (still) broken versions (see comments):
date('Y-m-d\TH:i:s') . substr(microtime(), 1, 8) . date('P')
Or, to avoid two calls to date:
date(sprintf('Y-m-d\TH:i:s%sP', substr(microtime(), 1, 8)))
Best performance:
substr_replace(date('c'), substr(microtime(), 1, 8), 19, 0);
By doing separate [date] calls you have a small chance of two time stamps being out of order: eg call date at 1:29:22.999999 and mircotime at 1:29:23.000001. On my server consecutive calls are about 10 us apart.
Source
Try this instead:
list($usec, $sec) = explode(" ", microtime());
echo date("Y-m-d\TH:i:s", $sec) . substr($usec, 1, 8) . date("P", $sec);
E.g.:
2015-07-19T16:59:16.0113674-07:00
As a solution for 2020 with the DateTime class, which was added in PHP 5.2, you can do a simple one liner to get the wanted format.
For example:
echo (new DateTime())->format('Y-m-d\TH:i:s.uP');
// 2020-04-23T09:18:25.311075+02:00
The DateTimeInterface, which is implemented by the DateTime class, brings its own constants for widely used date formats. If you know the format, you can use a constant for that.
echo var_dump($datetime->format(DateTime::RFC3339_EXTENDED));
// 2020-04-23T09:18:25.311+02:00
As object orientated programming is widely spread in the PHP world, this could be a possible solution, too.
If parsing the string returned by microtime makes you vomit in your mouth, and you don't want multiple distinct timestamps munged together into your output, you can do this:
$unow = microtime(true);
sprintf("%s.%06d%s", date("Y-m-d\TH:i:s", $unow), ($unow - floor($unow))*1e6, date("P", $unow));
I had a series of data (class_time) store in php. And I wish to compare the day and time to prevent time collison when supervisor create the class. So I use the list() & split() functions to separate my data. The format of data is
Fri, 11:00-13:00
And this is the code that I use to trace it.
while($row8=mysqli_fetch_assoc($result8){
$preclasstime=$row8['class_time'];
list($day, $starthrs,$startmin,$endhrs,$endmin) = split('[,:-:]', $preclasstime);
if($day==$_POST['csday']){
$numstarthrs=(int)$starthrs;
$numstartmin=(int)$startmin;
$tottimestart=($numstarthrs*100)+($numstartmin);
$numendhrs=(int)$endhrs;
$numendmin=(int)$endmin;
$tottimeend=($numendhrs*100)+($numendmin);
echo "$numendmin \n";
}
However, after I execute it, it can obtain the $day, $starthrs, $startmin successfully, but when turn into $endhrs, $endmin, it cannot function well. It will skip one of the $endhrs and directly to the $endmin.
For example:
$tottimestart=1100 but $tottimeend=0000, it will ignore the 13.
The answer should be 1300.
If another example such as: Fri, 11:00-13:30 , $tottimeend should be equal to 1330.
I don't know where the error which to cause it to skip one of my value.
split() was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.
Alternatives to this function include: preg_split()
Here is the solution to your problem:
$keywords = preg_split('/[\s,\s:\s-\s:\s]+/', "Fri, 11:00-13:30");
$day = $keywords[0];
$tottimestart = $keywords[1]*100 + $keywords[2];
$tottimeend = $keywords[3]*100 + $keywords[4];
echo $day."<br />";
echo $tottimestart."<br />";
echo $tottimeend."<br />";
Use concatenator to join the strings before converting to interger
<?php
$data = "Fri, 11:00-13:30";
list($day, $starthrs,$startmin,$endhrs,$endmin) = preg_split('[,|:|-]', $data);
echo 'Day: ' . $day;
echo '<br>Start: ' . (int)$tottimestart = $starthrs . $startmin;
echo '<br>End: ' . (int)$tottimesend = $endhrs . $endmin;
?>
You can do it easily like this ,if the format you have specified would follow always:
<?php
$data = "Fri, 11:00-13:30";
list($day,$timingData) = explode(',', $data);
list($startTime,$endTime) = explode('-', $timingData);
$startTime = str_replace(':', '', $startTime);
$endTime = str_replace(':', '', $endTime);
echo "Day: $day <br/>";
echo "startTime: $startTime <br/>";
echo "endTime: $endTime";
?>
Output:
Day: Fri
startTime: 1100
endTime: 1330
Apply this pattern to preg_split():
/[ ,:-]+/
It will use one or more of the characters in the character class as the delimiter. This ensures that the space that trails the comma is removed as well.
Code: (Demo)
$row8['class_time']='Fri, 11:00-13:00';
var_export(preg_split('/[ ,:-]+/',$row8['class_time']));
Output:
array (
0 => 'Fri',
1 => '11',
2 => '00',
3 => '13',
4 => '00',
)
Of course, you can attach your list() call where I have var_export().
I have a range of dates in string format in the form of
'2014-10-12'
what i want to do is compare these dates so i can get the oldest and the youngest.
In PHP how do i convert these to a format where i can do the following?
$oldestdate;
$youngesdate;
//loop though all the dates
if($exampledate < $youngesdate)
$youesdate = $exampledate;
if($exampledate > $oldestdate)
$oldestdate = $exampledate;
Thanks
The nice thing about YYYY-MM-DD style dates is that they will always sort correctly, whether treated as text (as in your example), numbers (e.g. 20141012), or actual dates.
Thus, there's no need to do anything special to compare them as long as everything is the same format. Your code, as written, should work as-is (besides the typos for $youngestdate).
Note that if you want to do anything besides comparing them -- e.g. anything actually involving treating them like actual dates -- you will indeed want something like strtotime() or a mix of mktime() + substr()
have you tried strotime? reference http://php.net/manual/de/function.strtotime.php
then you can easily compare with <and > and so on.
have you tried checkdate(12, 31, 2000)? PHP.net Checkdate function
For years between 1 and 32767 inclusive.Check post 2 in the php.net link
You should use the DateTime class.
$arr = ['2012-10-12', '2004-10-12', '2014-08-12', '2014-09-12', '2014-09-13', '2014-09-11'];
$_now = new DateTime('now');
foreach ( $arr as $_t ) {
$d = new DateTime ( $_t );
if ( !isset($newest) || $d >= $newest ) $newest = $d;
if ( !isset($oldest ) || $d <= $oldest ) $oldest = $d;
}
echo 'Newest ' . $newest->format('Y-m-d');
echo 'Oldest' . $oldest->format('Y-m-d');
Take a look here: Reference on php.net
And here is an working example
How would you convert UK date to US date in PHP without much regard to separator:
e.g.
01/01/2012
to
2012-01-01
Thanks in advance!
If you don't have to invoke date and time functions, don't do it and according to your question it seems like you only need string manipulations. Use sscanf()
list($date,$month,$year) = sscanf("01/01/2012", "%d/%d/%d");
echo "$month-$date-$year";
You could use strtotime but that's a magical function so I don't trust it.
A more discreet approach is to just do a very manual conversion, like:
$us_date = "01/01/2012";
$parts = explode("/", $us_date, 3);
$uk_date = $parts[2] . "-" . $parts[0] . "-" . $parts[1]; // flip day and month?
<?php
$format1 = strtotime("01/01/2012");
//$format2 = strtotime("2012-01-01");
echo date("Y-m-d",$format1);
?>
How can I get php to not use 1.297503E+17 on large int but 129750300000000000
code:
$dag = 29;
$maand = 03;
$jaar = 2012;
$expdate = $dag . "-" . $maand . "-" . $jaar;
$unixstamp = strtotime($expdate);
echo $unixstamp."<br />";
$winstamp = ($unixstamp + 11644560000) * 10000000;
I'm trying to use the number for a Timestamp in ldap.
That's what I would do (tested on 32b platform)
>> number_format(1.297503E+17,0,'.','')
'129750300000000000'
just be aware, that what you get back is a string, an will be converted back to float if you try doing any arithemtics on it. If you need to do math on large integers look into bc_math extension
PHP internally uses big enough integers. Your problem here is the use of echo:
printf ("%d", $winstamp);
$winstamp++;
printf ("%d", $winstamp);
output:
129775320000000000
129775320000000001
Hope this helps
echo rtrim(sprintf("%0.15f", $winstamp), "0.");
This uses sprintf to print a maximum of 15 decimal places, and then trims off any trailing 0 or . chars. (Of course, there's no guarantee that everything will be rounded nicely with trailing zeros as you might expect.)
If you just want a fixed size, then you can adjust the 15 and remove the rtrim.
Apparently, when PHP encounters a number that exceeds the upper limit of 2,147,483,647 for an integer, it automatically converts the number’s type from integer into a double.
Fortunately, we can format these numbers in scientific notation back to their standard integer form using the number_format() function. Here is how to do it:
$winstamp = 1202400000;
$formatted_stamp = number_format($winstamp , 0, '.', '');
echo $formatted_stamp; //outputs 1202400000 as expected