What is the unix timestamp formula? - php

First of all, i know this question has been sort of asked/sort-of answered here: Calculate day number from an unix-timestamp in a math way? .
I need a custom function/formula for this. so it only returns a ISO format date. "YYYY-MM-DD".
eg. 1316278442 = 2011-09-17
EDIT by Ext!
THIS IS WRONG ! Please don't read this.
I've been at this all day! The only thing i managed to get out is the day of the week.
$dayOfWeek=($timestamp/86400)%7; //And here 1 is Saturday, 7 is Friday
Speed is the issue, that is why i don't want to use date('Y-m-d',$timestamp);
If you cannot help me whit a custom function or formula, at least give me a better explanation on how to do this. It was done in so many languages, there must be someone out there that knows how to do this.
Thank you in advance for your help.

Here is the function that date() and DateTime::setTimestamp() use to compute the date from a unix timestamp:
https://github.com/php/php-src/blob/d57eefe6227081001978c3a63224065af8b5728e/ext/date/lib/unixtime2tm.c#L39
As you can see, this is a bit complicated by leap years, etc.
--
That said, if you need only the day of the week, it seems that you can safely ignore leap years, and just use the formula you given in the question: $dayOfWeek=($timestamp/86400)%7

Ok. The function is complete. It takes a unix timestamp and returns a YYYY-MM-DD. This was all i needed. I hope it helps anyone ...
<?php
$t=1325522004;//return 2011-09-19
/*
* Transform a Unix Timestamp to ISO 8601 Date format YYYY-MM-DD
* #param unix timestamp
* #return Returns a formated date (YYYY-MM-DD) or false
*/
function unixToIso8601($timestamp){
if($timestamp<0){return false;}//Do not accept negative values
/* Too many constants, add this to a class to speed things up. */
$year=1970;//Unix Epoc begins 1970-01-01
$dayInSeconds=86400;//60secs*60mins*24hours
$daysInYear=365;//Non Leap Year
$daysInLYear=$daysInYear+1;//Leap year
$days=(int)($timestamp/$dayInSeconds);//Days passed since UNIX Epoc
$tmpDays=$days+1;//If passed (timestamp < $dayInSeconds), it will return 0, so add 1
$monthsInDays=array();//Months will be in here ***Taken from the PHP source code***
$month=11;//This will be the returned MONTH NUMBER.
$day;//This will be the returned day number.
while($tmpDays>=$daysInYear){//Start adding years to 1970
$year++;
if(isLeap($year)){
$tmpDays-=$daysInLYear;
}
else{
$tmpDays-=$daysInYear;
}
}
if(isLeap($year)){//The year is a leap year
$tmpDays--;//Remove the extra day
$monthsInDays=array(-1,30,59,90,120,151,181,212,243,273,304,334);
}
else{
$monthsInDays=array(0,31,59,90,120,151,181,212,243,273,304,334);
}
while($month>0){
if($tmpDays>$monthsInDays[$month]){
break;//$month+1 is now the month number.
}
$month--;
}
$day=$tmpDays-$monthsInDays[$month];//Setup the date
$month++;//Increment by one to give the accurate month
return $year.'-'.(($month<10)?'0'.$month:$month).'-'.(($day<10)?'0'.$day:$day);
}
function isLeap($y){
return (($y)%4==0&&(($y)%100!=0||($y)%400==0));
}
echo unixToIso8601($t);
?>

You could convert to julian first with unixtojd() and then use cal_from_jd to split into year,month,day.
It's a little faster. The code below gives me this result:
2009-02-13 0.13018703460693 seconds using date()
2009-02-13 0.037487983703613 seconds using unixtojd(),cal_from_jd(),and sprintf()
function microtime_float(){
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
$unix_timestamp = 1234567890;
for($i=0;$i<10000;$i++) {
$d = date('Y-m-d',$unix_timestamp);
}
$time_stop = microtime_float();
echo $d . " " . ($time_stop - $time_start) . " seconds using date()<br>\n";
//////////////////////////
$time_start = microtime_float();
$unix_timestamp = 1234567890;
for($i=0;$i<10000;$i++) {
$julian_date = unixtojd($unix_timestamp);
$date_array = cal_from_jd($julian_date, CAL_GREGORIAN);
$d = sprintf('%d-%02d-%02d',$date_array['year'],$date_array['month'],$date_array['day']);
}
$time_stop = microtime_float();
echo $d . " " . ($time_stop - $time_start) . " seconds using unixtojd(),cal_from_jd(),and sprintf()<br>\n";

Related

PHP Adding 15 minutes to Time value

I have a form that receives a time value:
$selectedTime = $_REQUEST['time'];
The time is in this format - 9:15:00 - which is 9:15am. I then need to add 15 minutes to this and store that in a separate variable but I'm stumped.
I'm trying to use strtotime without success, e.g.:
$endTime = strtotime("+15 minutes",strtotime($selectedTime)));
but that won't parse.
Your code doesn't work (parse) because you have an extra ) at the end that causes a Parse Error. Count, you have 2 ( and 3 ). It would work fine if you fix that, but strtotime() returns a timestamp, so to get a human readable time use date().
$selectedTime = "9:15:00";
$endTime = strtotime("+15 minutes", strtotime($selectedTime));
echo date('h:i:s', $endTime);
Get an editor that will syntax highlight and show unmatched parentheses, braces, etc.
To just do straight time without any TZ or DST and add 15 minutes (read zerkms comment):
$endTime = strtotime($selectedTime) + 900; //900 = 15 min X 60 sec
Still, the ) is the main issue here.
Though you can do this through PHP's time functions, let me introduce you to PHP's DateTime class, which along with it's related classes, really should be in any PHP developer's toolkit.
// note this will set to today's current date since you are not specifying it in your passed parameter. This probably doesn't matter if you are just going to add time to it.
$datetime = DateTime::createFromFormat('g:i:s', $selectedTime);
$datetime->modify('+15 minutes');
echo $datetime->format('g:i:s');
Note that if what you are looking to do is basically provide a 12 or 24 hours clock functionality to which you can add/subtract time and don't actually care about the date, so you want to eliminate possible problems around daylights saving times changes an such I would recommend one of the following formats:
!g:i:s 12-hour format without leading zeroes on hour
!G:i:s 12-hour format with leading zeroes
Note the ! item in format. This would set date component to first day in Linux epoch (1-1-1970)
strtotime returns the current timestamp and date is to format timestamp
$date=strtotime(date("h:i:sa"))+900;//15*60=900 seconds
$date=date("h:i:sa",$date);
This will add 15 mins to the current time
To expand on previous answers, a function to do this could work like this (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function here.)
// Return adjusted time.
function addMinutesToTime( $time, $plusMinutes ) {
$time = DateTime::createFromFormat( 'g:i:s', $time );
$time->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $time->format( 'g:i:s' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '9:15:00', 15 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
get After 20min time and date
function add_time($time,$plusMinutes){
$endTime = strtotime("+{$plusMinutes} minutes", strtotime($time));
return date('h:i:s', $endTime);
}
20 min ago Date and time
date_default_timezone_set("Asia/Kolkata");
echo add_time(date("Y-m-d h:i:sa"),20);
In one line
$date = date('h:i:s',strtotime("+10 minutes"));
You can use below code also.It quite simple.
$selectedTime = "9:15:00";
echo date('h:i:s',strtotime($selectedTime . ' +15 minutes'));
Current date and time
$current_date_time = date('Y-m-d H:i:s');
15 min ago Date and time
$newTime = date("Y-m-d H:i:s",strtotime("+15 minutes", strtotime($current_date)));
Quite easy
$timestring = '09:15:00';
echo date('h:i:s', strtotime($timestring) + (15 * 60));

Microtime to Relative Date Conversion

I am receiving the following value from a database which is a millsecond (microtime) value
1369057622.4679
I would like to output this in PHP to be
3 Day's ago
Essentially reading the milliseconds value and converting it to a relative date string, can anyone suggest an easy method to do this.
You may do the following:
$input = 1369057622.4679;
$diff = floor(($input-time())/86400); // calculating the difference
$result = abs($diff) . (abs($diff)==1 ? ' day ':' days ') . ($diff<=0 ? 'ago':'ahead'); // making the result.
echo $result; // output: 1 day ago

convert excel dateserial back to a readable date format

How do i convert this excel dataserial value 41225 back to date format 12-Nov-2012 using phpexcel and code igniter?
I have tried the following but it didn't work.
$G74 = $objPHPExcel->getActiveSheet()->getCell('B6')->getValue();
Dates in Excel are stored as number of days since 1st Jan 1900, except there is an off by one error due to 1900 not being a leap year. You can create therefore a DateTime object with this hack (valid for dates from 1st March 1900 onwards):
$n = 41225;
$dateTime = new DateTime("1899-12-30 + $n days");
You can format the DateTime Object with something like:
echo $dateTime->format("d M Y");
If you want to include the time as well as the date, multiply by 86400 (the number of seconds in a day) to get seconds since 1st Jan 1900 before you convert:
$n = 42898.35416666;
$dateTime = new DateTime("1899-12-30 + ". round($n * 86400) . " seconds");
Using the getFormattedValue() method rather than getValue() might help if the cell has a format mask that formats it as a date. getValue() returns a raw value, which (in this case) is the Excel serialized number.
Otherwise, the ExcelToPHP() or ExcelToPHPObject() methods in the PHPExcel_Shared_Date class should do the job of returning a unix timestamp or a PHP DateTime object that you can then format however you wish
I had to convert a dateserial number in decimal format ie: 42898.35416666 and the DateTime object does not take decimals.
Based on rjmunro's answer, and animuson's answer on how to convert decimals to hours and minutes, here is a solution for decimal Excel dates.
function dateSerialToDateTime($dateserial) {
$arrDate = explode(".", $dateserial);
$n = $arrDate[0];
$decimal = "." . $arrDate[1]; //decimal amount of seconds
$duration = 86400 * $decimal; //number of seconds in a day * decimal
$dateTime = new DateTime("1899-12-30 + $n days");
$converted = $dateTime->format("Y-m-d") . " " . gmdate("H:i:s", $duration);
return $converted;
}
$dateserial = 42898.35416666;
die(dateSerialToDateTime($dateserial));
//returns 2017-06-12 08:29:59

How to convert date into same format?

I want to get the $registratiedag and count a couple of days extra, but I always get stuck on the fact that it needs to be a UNIX timestamp? I did some google-ing, but I really don't get it.
I hope someone can help me figure this out. This is what I got so far.
$registratiedag = $oUser['UserRegisterDate'];
$today = strtotime('$registratiedag + 6 days');
echo $today;
echo $registratiedag;
echo date('Y-m-d', $today);
There's obviously something wrong with the strtotime('$registratiedag + 6 days'); part, because I always get 1970-01-01
You probably want this:
// Store as a timestamp
$registratiedag = strtotime($oUser['UserRegisterDate']);
$new_date = strtotime('+6 days', $registratiedag);
// You'll need to format for printing $new_date
echo date('Y-m-d', $new_date);
// I think you want to compare $new_date against
// today's date. I'd recommend a string comparison here,
// As time() includes the time as well
// time() is implied as the second argument to date,
// But we'll put it anyways just to be clearer
if( date('Y-m-d', $new_date) == date('Y-m-d', time()) ) {
// The dates are equal, do something here
}
else if($new_date < time()) {
// if the new date is earlier than today
}
// etc.
First it converts $registratiedag to a timestamp, then it adds 6 days
EDIT: You probably should change $today to something less misleading like $modified_date or something
try:
$today = strtorime($registratiedag);
$today += 86400 * 6; // seconds in 1 day * 6 days
at least one of your problems is that PHP does not expand variables in single quotes.
$today = strtotime("$registratiedag + 6 days");
//use double quotes and not single quotes when embedding a php variable in a string
If you want to include the value of variable $registratiedag right into the text passed as parameter of strtotime, you have to enclose that parameter with ", not with '.

How to get millisecond between two dateTime obj?

How to get millisecond between two DateTime objects?
$date = new DateTime();
$date2 = new DateTime("1990-08-07 08:44");
I tried to follow the comment below, but I got an error.
$stime = new DateTime($startTime->format("d-m-Y H:i:s"));
$etime = new DateTime($endTime->format("d-m-Y H:i:s"));
$millisec = $etime->getTimestamp() - $stime->getTimestamp();`
I get the error
Call to undefined method DateTime::getTimestamp()
In the strict sense, you can't.
It's because the smallest unit of time for the DateTime class is a second.
If you need a measurement containing milliseconds then use microtime()
Edit:
On the other hand if you simply want to get the interval in milliseconds between two ISO-8601 datetimes then one possible solution would be
function millisecsBetween($dateOne, $dateTwo, $abs = true) {
$func = $abs ? 'abs' : 'intval';
return $func(strtotime($dateOne) - strtotime($dateTwo)) * 1000;
}
Beware that by default the above function returns absolute difference. If you want to know whether the first date is earlier or not then set the third argument to false.
// Outputs 60000
echo millisecsBetween("2010-10-26 20:30", "2010-10-26 20:31");
// Outputs -60000 indicating that the first argument is an earlier date
echo millisecsBetween("2010-10-26 20:30", "2010-10-26 20:31", false);
On systems where the size of time datatype is 32 bits, such as Windows7 or earlier, millisecsBetween is only good for dates between 1970-01-01 00:00:00 and 2038-01-19 03:14:07 (see Year 2038 problem).
Sorry to digg out an old question, but I've found a way to get the milliseconds timestamp out of a DateTime object:
function dateTimeToMilliseconds(\DateTime $dateTime)
{
$secs = $dateTime->getTimestamp(); // Gets the seconds
$millisecs = $secs*1000; // Converted to milliseconds
$millisecs += $dateTime->format("u")/1000; // Microseconds converted to seconds
return $millisecs;
}
It requires however that your DateTime object contains the microseconds (u in the format):
$date_str = "20:46:00.588";
$date = DateTime::createFromFormat("H:i:s.u", $date_str);
This is working only since PHP 5.2 hence the microseconds support to DateTime has been added then.
With this function, your code would become the following :
$date_str = "1990-08-07 20:46:00.588";
$date1 = DateTime::createFromFormat("Y-m-d H:i:s.u", $date_str);
$msNow = (int)microtime(true)*1000;
echo $msNow - dateTimeToMilliseconds($date1);
DateTime supports microseconds since 5.2.2. This is mentioned in the documentation for the date function, but bears repeating here. You can create a DateTime with fractional seconds and retrieve that value using the 'u' format string.
<?php
// Instantiate a DateTime with microseconds.
$d = new DateTime('2011-01-01T15:03:01.012345Z');
// Output the microseconds.
echo $d->format('u'); // 012345
// Output the date with microseconds.
echo $d->format('Y-m-d\TH:i:s.u'); // 2011-01-01T15:03:01.012345
// Unix Format
echo "<br>d2: ". $d->format('U.u');
function get_data_unix_ms($data){
$d = new DateTime($data);
$new_data = $d->format('U.u');
return $new_data;
}
function get_date_diff_ms($date1, $date2)
{
$d1 = new DateTime($date1);
$new_d1 = $d1->format('U.u');
$d2 = new DateTime($date2);
$new_d2 = $d2->format('U.u');
$diff = abs($new_d1 - $new_d2);
return $diff;
}
https://www.php.net/manual/en/class.datetime.php
Here's a function to do that + tests.
https://gist.github.com/vudaltsov/0bb623b9e2817d6ce359eb88cfbf229d
DateTime dates are only stored as whole seconds. If you still need the number of milliseconds between two DateTime dates, then you can use getTimestamp() to get each time in seconds (then get the difference and turn it into milliseconds):
$seconds_diff = $date2.getTimestamp() - $date.getTimestamp()
$milliseconds_diff = $seconds_diff * 1000

Categories