I have a date calendar in my php form which gives me date '19-05-2014'. I should compare this date to database time-modified (1400481271) exactly.
When converted '19-05-2014' to UNIX TIME STAMP, but I get the result as 1397858400 which was a wrong time stamp.
id userid timemodified
370 23 1400481271
329 24 1427771915
333 30 1428309816
332 32 1428303307
327 33 1427689703
328 34 1427710711
<?php
if ( preg_match('/^(?P<day>\d+)[-\/](?P<month>\d+)[-\/](?P<year>\d+)$/', '19-05-2014', $matches) )
{
$timestamp = mktime(0, 0, 0, ( $matches['month'] - 1 ), $matches['day'], $matches['year']);
echo $timestamp;
}
?>
The date you are trying to match is, converted to timestamp:
1400457600
If you got a different value you converted it wrong (maybe switched day and month or something similar).
It is, however, while close, still not identical to the given value 1400481271 in your database.
The reason for this becomes clear if you convert it back to a readable date:
05/19/2014 # 6:34am (UTC) 1400481271
For comparison, the given date:
05/19/2014 # 12:00am (UTC) 1400457600
As you can see there is a difference because it's the same date, but a different time.
The easiest way would be to retrieve only the date portion from the database.
You can do this in your SQL query like this:
SELECT DATE( FROM_UNIXTIME( timemodified ) ) AS modified
This will return 2014-05-19, which you can easily compare with your string.
Or, if you can even retrieve it in the same format you get it, so you don't need to rewrite your date with regex:
SELECT DATE_FORMAT( FROM_UNIXTIME( timemodified ), '%d-%m-%Y' ) AS modified
This will return 19-05-2014 for 1400481271.
Related
I am trying to implement a settlement date algorithm to check for local public holidays in my region for a small trading application built in php/mysql. I have all local public holiday dates stored neatly in my db and then i output using a variable.
The application should check the current date and then add three working days (Minus weekends) as the settlement cycle in my country follows a t+3 settlement rule for all trades. This requires that if the settlement should fall on a public holiday or weekend, the application should compare the dates in the db table and then set a new working day as the settlement date.
can someone please help me with what i may be missing? Please find the code below:
<?php
$rsd = date ( 'Ymd' , strtotime ( '3 weekdays' ) );
$phd = $row_public_holidays['date'];
if ($rsd == $phd) {
echo date ( 'Ymd' , strtotime ( '4 weekdays' ) );
} else {
echo date ( 'Ymd' , strtotime ( '3 weekdays' ) );
}
?>
If you need the output of date to have 8 digits, you can update the format string from Ymj to Ymd. Changing the last character from j to d moves from showing:
Day of the month without leading zeros
to:
Day of the month, 2 digits with leading zeros
As per the documentation for date (http://php.net/manual/en/function.date.php).
Putting this together
The call to strtotime performs the calculation and returns an integer representing the seconds since epoch in the determined (or provided) timezone (http://php.net/manual/en/function.strtotime.php). The call to date is simply to format that integer into a string based on the provided format (http://php.net/manual/en/function.date.php).
So:
$time = strtotime('4 weekdays');
var_dump($time);
$date1 = date('Ymj', $time);
var_dump($date1);
$date2 = date('Ymd', $time);
var_dump($date2);
outputs:
int(1533600000)
string(7) "2018087"
string(8) "20180807"
In this example, the calls to date don't change the value of $time.
I am trying to check if one date is equal than the other date, but I can't get the match because the date format coming from the form turns into a different order once it gets through the "parse" code.
I need to format this date to find the match, here is a sample code to show how I am trying:
...
// $ago will give me this date: 2016-12-09 00:00:00
$ago = Carbon\Carbon::today()->addDays(2); // Todays date + 2 days
//$request->datex has the date coming from a form with this format, '12-06-2016'.
// Once a parse $request->datex here, the date gets out of order:
$my_date = Carbon\Carbon::parse($request->datex);
// it shows the date like this, 2016-09-12 00:00:00 , I need it to be on this format: 2016-12-09 00:00:00
// then I could do this:
if ( $ago$ == $my_date ) {
dd($my_date.' is equal to: '.$ago );
}else{
dd(' Not equal!');
}
...
Thanks for looking!
Change this line
$my_date = Carbon\Carbon::parse($request->datex);
with this:
$my_date = Carbon::createFromFormat('m-d-Y', $request->datex)
I've assumed that your format '12-06-2016' means DAY-MONTH-YEAR
UPDATE
Tested my solution on my machine and it works, date is recognized properly:
When
$request->datex = '12-06-2016'
then
$my_date = \Carbon\Carbon::createFromFormat('m-d-Y', $datex);
gives me date like that: public 'date' => string '2016-12-06 18:52:09.000000' (length=26)
Date has been parsed properly. The thing that I've assumed just now. These dates won't be same cause of hours, minutes, seconds and milliseconds. To fix that just we have to compare dates that way:
if ( $ago->format('Y-m-d') == $my_date->format('Y-m-d') )
//do something awesome with our equal dates
PHP expects DD-MM-YYYY or MM/DD/YYYY formats.
If you always have a MM-DD-YYYY format, you could do this before parsing:
$request->datex = str_replace('-', '/', $request->datex);
I have two times saved in database as
DayTime1 = "Wed 09:00"
DayTime2 = "Wed 13:00"
I want to get the difference between these two dates in minutes.
TIMESTAMPDIFF(MINUTES,DayTime1,DayTime2) return null
I'm not able to get through it. Is there any way to get difference?
Please note, that SELECT STR_TO_DATE("Wed 09:00", "%a %H:%i") returns 0000-00-00 09:00:00 (at least on my local MySql 5.5.16). So if comparing different days, you won't get the correct result.
If given a year and week, the day name will be interpreted to a real date, so comparisons may also span days. For example (though not really elegant, I admit):
SELECT TIMESTAMPDIFF(MINUTE,
STR_TO_DATE(CONCAT(YEAR(CURDATE()), WEEKOFYEAR(CURDATE()), ' Tue 09:00'), '%x%v %a %H:%i'),
STR_TO_DATE(CONCAT(YEAR(CURDATE()), WEEKOFYEAR(CURDATE()), ' Wed 13:00'), '%x%v %a %H:%i')
)
Since you also included the php-tag, I'm assuming a PHP solution is valid as well:
$daytime1 = "Wed 09:00";
$daytime2 = "Wed 13:00";
$diff = abs(strtotime($daytime1) - strtotime($daytime2)); //absolute diff in seconds
$diff = $diff / 60; //Difference in minutes
EDIT:
And here is a pure MySQL solution:
SELECT ABS(
TIME_TO_SEC(
TIMEDIFF(
STR_TO_DATE("Wed 09:00", "%a %H:%i"),
STR_TO_DATE("Wed 13:00", "%a %H:%i")
)
)
) / 60
The second parameter, "%a %H:%i"is the date format. If it's always in the format of "First three letters of weekday, space, hour with leading zero, :, minutes" then you can use this format.
I have 2 values stored in a database. One is a startdate, the other an enddate.
Now when the Year, month and date of the 2 are equal. I would like the enddate to only show the time.
For example
maandag 16 juni 14:06 tot maandag 16 juni 14:15
would be
maandag 16 juni 14:06 tot 14:15.
I'm pretty new at PHP. I've tried the following statement, but i'm pretty sure it's incorrect:$
<?php if($item->startdate("Ymd") == ($item->enddate("Ymd"))): ?>
The type of the values are DateTime
You could also try using the substr-function, only comparing portions of the variables:
if(substr($item->startdate, 0, 10) == substr($item->enddate, 0, 10))
Here we compare the first ten characters (YYYY-MM-DD) of $item->startdate and $item->enddate.
<?php if(date('Y-m-d',strtotime($item->startdate) == date('Y-m-d',strtotime($item->enddate))) : ?>
Try
if(date('Ymd',strtotime($item->startdate)) == date('Ymd',strtotime($item->enddate))) :
The date function should take almost any data format and reformat it to the format you give it i.e. 'Ymd'
PHP Manual for the date() function
I wanted to know if there is a way to get the time zone offset for a given date range between two timezones for a given duration.
getTimezoneOffset(startDate,endDate,timezone1,timezone2){
...missing magic to go here...
}
should return the time zone offset which is valid for the a given duration. However if the offset changes, it should return the date range for which it's valid.
So I am looking at something like this:
getTimezoneOFfset("march 9 12 am", "march 15 12 am", "UTC", "US/NEW_YORK")
return value something like this
timezoneoffset[0]["range"]=[march 9 12am to march 11 2 am]
timezoneoffset[0]["offset"]=5
timezoneoffset[1]["range"]=[march 9 2 am to march 15 12 am]
timezoneoffset[1]["offset"]=4
I just don't want to calculate timezone offsets for every scheduled item for the given range. Was looking if there is some way to get a direct lookup for offsets if it's going to change.
I am working with PHP, but a solution in any language will be appreciated.
MySQL solution will also work as it will be more optimized to do this in MySQL.
Assuming that you have a newer version of php (5.2.0+) the DateTimeZone class is part of the PHP core and will let you use the getOffset() function to make these calculations. It will let you pass in a dateTime object and specify a timezone. If you do this for both your dates you should be able to calculate all of the pieces you're looking to grab. To use an example from php.net:
// Create two timezone objects, one for Taipei (Taiwan) and one for
// Tokyo (Japan)
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");
// Create two DateTime objects that will contain the same Unix timestamp, but
// have different timezones attached to them.
$dateTimeTaipei = new DateTime(mktime([the date in question]), $dateTimeZoneTaipei);
$dateTimeJapan = new DateTime(mktime([the date in question]), $dateTimeZoneJapan);
// Calculate the GMT offset for the date/time contained in the $dateTimeTaipei
// object, but using the timezone rules as defined for Tokyo
// ($dateTimeZoneJapan).
$timeOffset = $dateTimeZoneJapan->getOffset($dateTimeTaipei);
// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
print("Number of seconds Japan is ahead of GMT at the specific time: ");
var_dump($timeOffset);
print("<br />Number of seconds Taipei is ahead of GMT at the specific time: ");
var_dump($dateTimeZoneTaipei->getOffset($dateTimeTaipei));
print("<br />Number of seconds Japan is ahead of Taipei at the specific time: ");
var_dump($dateTimeZoneJapan->getOffset($dateTimeTaipei)
-$dateTimeZoneTaipei->getOffset($dateTimeTaipei));
This working for me:
function Get_Timezone_Offset($remote_tz, $origin_tz = null)
{
if($origin_tz === null)
{
if(!is_string($origin_tz = date_default_timezone_get())) {
return false;
}
}
$origin_dtz = new DateTimeZone($origin_tz);
$remote_dtz = new DateTimeZone($remote_tz);
$origin_dt = new DateTime("now", $origin_dtz);
$remote_dt = new DateTime("now", $remote_dtz);
$offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
return $offset;
}
To use it
echo Get_Timezone_Offset('America/New_York', 'Europe/Stockholm');
Source:
http://php.net/manual/en/function.timezone-offset-get.php
I think PHP's DateTimeZone::getTransitions method can get you there. It has a procedural alias, timezone_transitions_get().
public array DateTimeZone::getTransitions (
[ int $timestamp_begin [, int $timestamp_end ]] )
This method returns all "transitions" from one time zone offset value to another, for that timezone, in a given time range.
For your purposes, you will want to create DateTimeZone objects for each of your time zones, call DateTimeZone::getTransitions for your date range to get an array of transitions for that time zone, then merge and sort the two arrays of transitions. This will give you the equivalent of the timezoneoffset[] array you seek.
Something like:
getTimezoneOffset(startDate,endDate,timezone1,timezone2){
DT1 = DateTimeZone( timezone1 );
transitions1 = DT1->getTransitions( startDate,endDate );
DT2 = DateTimeZone( timezone2 );
transitions1 = DT2->getTransitions( startDate,endDate );
timezoneoffset[] = // merge and sort (transitions1, transitions2)
}
The format of the transitions array isn't well documented. The method documentation shows some example entries:
Array
(
...
[1] => Array
(
[ts] => -1691964000
[time] => 1916-05-21T02:00:00+0000
[offset] => 3600
[isdst] => 1
[abbr] => BST
)
[2] => Array
(
[ts] => -1680472800
[time] => 1916-10-01T02:00:00+0000
[offset] => 0
[isdst] =>
[abbr] => GMT
)
...
)
I speculate that: ts refers to a PHP timestamp in epoch seconds, as returned by time(), giving the instant in time at which the offset changes to the value in this record. time refers to the same instant, as a formatted string date-time. offset is the timezone's offset in seconds from UTC, as of the instant time/ts, forward to the next transition. isdst is 1 if the offset refers to a daylight savings time offset, 0 otherwise. abbr is a string abbreviation for the time zone. If anyone has solid information about this data structure, it would be a kindness to add it to the documentation.