function convertDT($TS) {
$TS = strtotime($TS);
$TS -= date("Z");
$newTS = date("Y-m-d\TH:i:s\Z", $TS);
return $newTS;
}
echo "Good: ".convertDT('2010-04-20 01:23:45')."\n";
echo "Bad: ".convertDT('2010-31-20 01:23:45')."\n";
The second date returns: 1969-12-31T23:00:00Z
Why? Should this error?
strtotime() returns false when you give it an invalid timestamp. false is equivalent to 0 if you use it in an integer context, so when you pass it to this line:
$newTS = date("Y-m-d\TH:i:s\Z", $TS);
You are effectively creating a date from a timestamp of 0. In terms of the UNIX epoch, 0 is January 1st, 1970, which is where you're getting your end result from.
Your best bet would be soemthing like this:
$TS = strtotime($TS);
if($TS === false) {
throw new Exception("Invalid timestamp.");
}
//etc.
On your second date, you are trying to create a date of month 31 and of day 20. Even if you reversed these, it wouldn't make sense. Probably a typo.
read this http://php.net/manual/en/function.strtotime.php
Errors/Exceptions
Every call to a date/time function
will generate a E_NOTICE if the time
zone is not valid, and/or a E_STRICT
or E_WARNING message if using the
system settings or the TZ environment
variable. See also
date_default_timezone_set()
This function will not generate any error even if input string is not valid.
Related
I want to compare the file modification date with the current date.
I tried the following (which is working for the current Time):
$currentDay = date("d");
$currentMonth = date("m");
$currentYear = date("y");
$currentHour = date("h");
$currentMinute = date("i");
Now i tried to get the file modification year from my file:
$subst1 = file("f1/subst_001.htm");
$mod_date=date("y", filemtime($subst1));
echo $mod_date;
But it's giving me for year "70", which is coming from the Year 1970, what did i do wrong?
And no, i already checked if the file says this creation year...
The filetime() function expects string as file path. Here you are trying to pass an array that is returned from file()
Try like this way,
$filename= "f1/subst_001.htm";
if (file_exists($filename)) {
$mod_date = date("y", filemtime($filename));
echo $mod_date;
}
January 1, 1970 is the so called Unix epoch. It's the date where they
started counting the Unix time. If you get this date as a return
value, it usually means that the conversion of your date to the Unix
timestamp returned a (near-) zero result. So the date conversion
doesn't succeed. Most likely because it receives a wrong input.
Courtesy : Oldskool
Use the correct date format parameter.
'y' returns a two digit representation of the year:
date ("y", filemtime($filename)) // 18
'Y' returns the four digit representation of the year:
date ("Y", filemtime($filename)) // 2018
Try this:
$mod_date=date("y", filemtime("f1/subst_001.htm"));
echo $mod_date;
filemtime() takes string:pathname as its parameter but file() function reads a file into an array. Hope that helps.
Try using var_dump on the filemtime result - it is probably false (or something which converts to int 0). Since time 0 is January 1, 1970, that would explain why the year is '70'.
If that's the case, it's not finding your file.
I want to detect if a string is a time (00:18:31). I know about strtotime() but it also detects "now" as OK, and so on. I need a real solution.
Try this:-
if (DateTime::createFromFormat('H:i:s', $yourtimeString) !== FALSE) {
echo "it's a date";
}else{
echo "it's not a date";
}
Input:- 00:18:31 Output:- it's a date
Input:- now,NOW,now(),NOW() Output:- it's not a date
The validateTime() function checks whether the given string is a valid time. using DateTime class and createFromFormat() static method.
function validateTime($time, $format = 'H:i:s'){
$t = DateTime::createFromFormat($format, $time);
return $t && $t->format($format) === $time;
}
// Returns true
echo var_dump(validateTime("00:18:31"));
echo var_dump(validateTime("23:59:59"));
echo var_dump(validateTime("00:02:30"));
// Returns false
echo var_dump(validateTime("31:18:31"));
echo var_dump(validateTime("24:00:00"));
echo var_dump(validateTime("23:60:60"));
Explanation of $t->format($format) === $time
is a test to check if the time is indeed a real time or not. for instance 23:59:59 is valid time but 24:00:00 is not.
We all know that 23:59:59 is the max acceptable Human time. and 24:00:00 is not. However, We can pretend it means the next day at 00:00:00. that is what DateTime::createFromFormat do! when we give it a time exceed the maximum. It accept it by adding the remaining time to the next day.
For example
today is 2021-05-14 23:59:59
and time to check if we give it to createFromFormat is 24:02:30 the date becomes next day 2021-05-15 00:02:30
We notice that 24:02:30 != 00:02:30. So from that we can summarize that is not valid time. To be valid it must be the same!
this code keeps telling me that $lasUpdate is always greater than $yesterday no matter the change i make to $yesterday result is (12/31/14 is greater than 01/19/15 no update needed). i feel like i'm missing something simple thank you in advance it is greatly appreciated.
$result['MAX(Date)']='12/31/14';
$lastUpdate = date('m/d/y', strtotime($result['MAX(Date)']));
$yesterday = date('m/d/y', strtotime('-1 day'));
if($lastUpdate<$yesterday){echo $lastUpdate.'is less '.$yesterday.'<br>'.'update needed';}
if($lastUpdate>=$yesterday){echo $lastUpdate.'is greater than '.$yesterday.'<br>'.'no update needed';
You have fallen victim to PHP type juggling with strings. A date function has a return value of a string. You cannot compare dates in their string format since PHP will juggle strings into integers in the context of a comparison. The only exception is if the string is a valid number. In essence, you are doing:
if ('12/31/14' < '01/19/15') { ... }
if ('12/31/14' >= '01/19/15') { ... }
Which PHP type juggles to:
if (12 < 1) { ... }
if (12 >= 1) { ... }
And returns false on the first instance, and true on the second instance.
Your solution is to not wrap date around the strtotime functions, and just use the returned timestamps from the strtotime functions themselves to compare UNIX timestamps directly:
$lastUpdate = strtotime($result['MAX(Date)']);
$yesterday = strtotime('-1 day');
You will however want to use date when you do the echo back to the user so they have a meaningful date string to work with.
Try something like this:
$lastUpdate = strtotime($result['MAX(Date)']);
$yesterday = strtotime('-1 day');
if ($lastUpdate < $yesterday) { /* do Something */ }
12/31/14 is greater than 01/19/15
Because 1 is greater than 0. If you want to compare dates that way you will need to store them in a different format (from most to least significant digit), for example Ymd.
Or store the timestamps you are making in the different variables and compare them.
I have time saved in database like 7:30pm as a varchar field. I want to check if this time is greater than time right now or not.
I converted the DB time string into '19:30' and now I want to do something like this:
$my_time = '19:30';
if($my_time > date('H:i'))
{
do something ...
}
The problem is the above will return always true if $my_time is non-empty string.
doing strtotime($my_time) is not helping either.
strtotime('H:i',$my_time) makes it 00:00 .
doing (int)date('H:i') will give 1700 when the actual time is 17:09, so removing colon and then comparing will not work too ....
Changing database time data is out of question in this context.
plz help. Correct me if I stated some facts wrong.
You can use this:
$myTime = '19:30';
if (date('H:i') == date('H:i', strtotime($myTime))) {
// do something
}
You can construct a new DateTime object, setting the time on a random date. Than compare those two objects. eg:
$my_time = new DateTime('January 1th 1970 19:30');
$comparable_time = new DateTime('January 1th 1970 '. date('H:i'));
if($my_time < $comparable_time) {
// do something
} else {
// do something else
}
Please take note of the changelog;
Version 5.2.2 DateTime object comparison with the comparison operators changed to work as expected. Previously, all DateTime objects were considered equal (using ==).
You can't use the comparison operators with strings like that, because when you do the strings get converted to numbers first.
For an one-liner solution, you can use strcmp:
if(strcmp($my_time, date('H:i')) == 1)
{
do something ...
}
The condition above is semantically equivalent to "if $my_time is greater than the current time", but only if the format of the strings remains consistent! It's very easy to introduce a bug in this code if for any reason the format of $my_time does not directly correspond to the H:i pattern.
Dumbing down the values to strings is usually not the way you should be going about using dates and times. A more appropriate solution would be to use the native DateTime class, introduced in PHP 5.2.0 (John Conde has already given an example in his answer).
However, there is also one possible advantage to treating times as dumb scalar values: the results are consistent with the human perception that 01:00 is always later than 00:00. DateTime approaches are dependent on the local timezone and date, and might not always give you the expected results. Example:
// assume we are in London
date_default_timezone_set('Europe/London');
// assume that today is March 25, 2012
$date1 = new DateTime("2012-03-25 01:00:00");
$date2 = new DateTime("2012-03-25 02:00:00");
// and...
if ($date1 == $date2) {
echo "WTF?!? Equal???";
}
See it in action.
The result of this test is different than what comparing some scalar representation of "01:00" and "02:00", so it's a good idea to think about what the proper semantics are for the comparison.
$date1 = DateTime::createFromFormat('H:i', $my_time1);
$date2 = new DateTime();
if ($date1 > $date2)
{
// do something
}
Don't compare strings which represent timestamps. Instead, use strtotime() to convert any such strings to Unix timestamps, which are just numbers, and then compare these. You can get the Unix timestamp for the current time with time():
$my_time = '19:30';
if (strtotime($my_time) > time()) {
// do something ...
}
In PHP, you can tell if a given date is during the Daylight Savings Time period by using something like this:
$isDST = date("I", $myDate); // 1 or 0
The problem is that this only tells you whether that one point in time is in DST. Is there a reliable way to check whether DST is in effect at any time in that timezone?
Edit to clarify:
Brisbane, Australia does not observe daylight savings at any time of the year. All year around, it is GMT+10.
Sydney, Australia does, from October to March when it changes from GMT+10 to GMT+11.
I'm wondering if there would be some existing method, or a way to implement a method which works as such:
timezoneDoesDST('Australia/Brisbane'); // false
timezoneDoesDST('Australia/Sydney'); // true
I've found a method which works using PHP's DateTimezone class (PHP 5.2+)
function timezoneDoesDST($tzId) {
$tz = new DateTimeZone($tzId);
$trans = $tz->getTransitions();
return ((count($trans) && $trans[count($trans) - 1]['ts'] > time()));
}
or, if you're running PHP 5.3+
function timezoneDoesDST($tzId) {
$tz = new DateTimeZone($tzId);
return count($tz->getTransitions(time())) > 0;
}
The getTransitions() function gives you information about each time the offset changes for a timezone. This includes historical data (Brisbane had daylight savings in 1916.. who knew?), so this function checks if there's an offset change in the future or not.
Actually nickf method didn't works for me so I reworked it a little ...
/**
* Finds wherever a TZ is experimenting dst or not
* #author hertzel Armengol <emudojo # gmail.com>
* #params string TimeZone -> US/Pacific for example
*
*/
function timezoneExhibitsDST($tzId) {
$tz = new DateTimeZone($tzId);
$date = new DateTime("now",$tz);
$trans = $tz->getTransitions();
foreach ($trans as $k => $t)
if ($t["ts"] > $date->format('U')) {
return $trans[$k-1]['isdst'];
}
}
// Usage
var_dump(timezoneExhibitsDST("US/Pacific")); --> prints false
var_dump(timezoneExhibitsDST("Europe/London")); --> prints false
var_dump(timezoneExhibitsDST("America/Chicago")); --> prints false
same function call will return true in 1 month (March) hope it helps
DateTimeZone::getTransitions might help.
You could probably wing it:
$hasDst = date("I", strtotime('June 1')) !== date("I", strtotime('Jan 1'));
Otherwise you'd need to parse the text-based zoneinfo data files.
I don't think so, but since almost every country that observes DST changes its time for an entire season or two, you could try to test 4 points during any given year.
For example, test date("I", $date) for 2009/01/01, 2009/04/01, 2009/07/01 and 2009/10/01. If that timezone falls into DST, then at least one of those dates will return 1.
date has to be on the user/server timezone for it to work, and you can't use a range with date as you do with getTransitions