The Unix Time Stamp generated by my MKTIME is not generating correctly
(European format)
Date Submitted: 15/02/2014 19:00
Unix Code: 1392508800
This returned date is: 16/02/2014 00:00:00
Code it should of returned is: 1392490800
Code Used
After form is submitted values are captured and assigned...
if ($_POST['Callbacl']){
$CID=$_POST['ID'];
$Notes = $_POST['callbacknotes'];
$Time_H = $_POST['Time_Hour'];
$Time_M = $_POST['Time_Minute'];
$Date_Day = $_POST['Date_Day'];
$Date_Month = $_POST['Date_Month'];
$Date_Year = $_POST['Date_Year'];
$Appt = mktime($Time_H, $Time_M,00, $Date_Month, $Date_Day, $Date_Year);
echo $Appt . "<br>";
die;
}
Post values
Array (
[ID] => 1
[Time_Hour] => 19
[Time_Minute] => 00
[Date_Month] => 02
[Date_Day] => 15
[Date_Year] => 2014
[callbacknotes] =>
[Callback] => Call Back
)
I suppose to your time zone in php.ini is not your preferred one.
Try to set a proper time zone in php.ini or to add the following code at the beginning of your block.
date_default_timezone_set('your time zone');
There is the list of supported time zones in PHP:
http://www.php.net/manual/en/timezones.php
Related
i have simple php script where i have this variable
$date = date('Y-m-d', time());
The Problem: The variable is storing date as per my server timezone.
What is want: I want to store date as per user time zone, take a look into
example below:
1- tom checkin from USA
2- jenne checkin from Asia
since there is 12 hrs. difference so the date will be different too sometime
here is found some example but it's not dynamic
Converting GMT time to local time using timezone offset in php
offset = '-0500';
$isDST = 1; // Daylight Saving 1 - on, 0 - off
$timezoneName = timezone_name_from_abbr('', intval($offset, 10) * 36, $isDST);
$timezone = new DateTimeZone($timezoneName);
Then you can use it in a DateTime constructor, e.g.
$datetime = new DateTime('2012-04-21 01:13:30', $timezone);
Now what exactly i am looking,
1- in case of TOM $date should be 18
11:38 PM
Tuesday, 18 April 2017 (GMT-5)
Time in Chicago, IL, USA
2- in case of jenne $date should be 19
9:40 AM
Wednesday, 19 April 2017 (GMT+5)
Time in Lahore
difficult writing code in the comments section so i posted a working answer for you here
<?php
// here $usertimezone should be set = to what you have in your database
$usertimezone="Asia/Shanghai";
date_default_timezone_set('"'.$usertimezone.'"');
//new date and time
$ndate= new datetime();
//split into date and time seperate
$nndate =$ndate->format("Y-m-d");
$nntime= $ndate->format("H:i:S");
//here you can test it
echo $nndate;
echo $nntime;
?>
Use this function date_default_timezone_set for setting timezone, From this function you can set the timezone according to user and then get the required format.
Examples
<?php
date_default_timezone_set("new/timezone");//set the name of timezone here example Asia/Kokata
echo $date= date("Y-m-d H:i:s");
I am working on a WordPress plugin that allows the user to select a time using a jQuery dropdown script. The time is a string in the format of "5 : 34 PM". I need to save that value to my mysql database in the datetime format.
So far, I can save the date and time but the AM/PM is not being factored in.
Here is my PHP function:
function db_tables_insert() {
global $wpdb;
$table_name = $wpdb->prefix . 'tweettweet';
$tweet = $_POST["tweet"];
$time = $_POST["timepicker"];
$time=preg_replace('/\s+/', '', $time);
$date = "2015-02-08:";
$datetime = $date.$time;
$wpdb->insert(
$table_name,
array(
'time' => $datetime,
'text' => $tweet,
)
);
}
In this example, the value saved to the database would be "2015-02-08 12:13:00" (assuming the user selected 12:13 for the time). The problem is, that value is the same whether the user selects 12:13 am or 12:13 pm.
I need a way to convert the string so that the "am/pm" is taken into consideration when saved to the database.
strtotime should be able to handle this.
echo date('Y-m-d H:i:s',strtotime('2014-12-12 12:34 AM'));
returns 2014-12-12 00:34:00
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.
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.
EDIT
Per the comment below, here's my attempt at splitting / combining / converting the string prior to implementing mktime...
$date1 = explode("T",'2005-03-27T00:00:00');
$date2 = explode("-", $date1[0]);
$try = mktime($time1,$time2,0,$date2[1],$date[2],$date[3]);
print $try;
// Prints out: 951793200
Original Question:
I've inherited a database and would like very much to convert the bizarre way the data is stored to something more mysql-friendly...
In the meantime, I get a text string (yes... text)... That I'd like to convert to unixtime...
So, I'll get a string that looks like this:
2005-03-27T00:00:00 03:00 AM
I'd like to convert it to:
1111885200
Dates and times always mess me up... I've done a number of things using strtotime and mktime, but can't get it formatted the way I want.
Well, this is how I would do it.
$ex = '2005-03-27T00:00:00 03:00 AM';
$format = '%Y-%m-%dT00:00:00 %H:%M %p';
$strf = strptime($ex, $format);
$date_str = $strf['tm_mon'] + 1 . '/' . $strf['tm_mday'] . '/' . ($strf['tm_year'] + 1900) . ' ' . $strf['tm_hour'] . ':' . $strf['tm_min'] . ':00';
echo $date_str;
echo "\n";
echo strtotime($date_str);
echo "\n";
echo date('m-d-Y H:i:s', 1111885200);
But, your desired result does not seem to be correct based on the date you posted.
OUTPUT
3/27/2005 3:0:00
1111921200
03-26-2005 17:00:00
You could write a litte converter script that does the task for you.
Please check the optional parameters of mktime
You could try to split your string in hour / minute / second / month / day / year and put that into mktime. Then mktime will give you the unix timestamp for that.
So, I'm not a fan of regular expressions unless absolutely necessary, but they might be necessary here to pick out the time zone piece.
preg_match("/(\d{4})-(\d{2})-(\d{2})(T\d{2}:\d{2}:\d{2}) (\d{2}:\d{2}) (AM|PM)/", '2005-03-27T00:00:00 03:00 AM',$matches);
Will give you $matches that look something like:
Array
(
[0] => 2005-03-27T00:00:00 03:00 AM
[1] => 2005
[2] => 03
[3] => 27
[4] => T00:00:00
[5] => 03:00
[6] => AM
)
I would feed those pieces into a DateTime object. Then you can output it into any format you want. You also may have to adjust that regex some so it can handle all your dates.
If the T00:00:00 part is useless, just remove it and use strtotime():
<?php
$date = '2005-03-27T00:00:00 03:00 AM';
$timestamp = strtotime(preg_replace('!T[^ ]+!', '', $date));
var_dump(date('d/m/Y H:i:s', $timestamp));
?>
This prints:
string(19) "27/03/2005 03:00:00"