jQuery datepicker convert to date() on PHP - php

I have a script that saves a date like this.
$date = date('i')+50;
When I store this on my database, I got something like 1382851302 which works great to compare for past and future just using > or <.
In other part of the script for the admin I'm using a filter based on jQuery datepicker. The problem is I can't convert the date selected there to the same date() format so I can compare the date, I think time is somehow involved here (i) and well I can't.
here is my bad try.
$iniciopub = date('Y-m-d',strtotime($_POST['iniciopub']));
$finpub = date('Y-m-d',strtotime($_POST['finpub']));
This is not working.. (it just store "1970" )
if I try this..
$iniciopub = date($_POST['iniciopub']);
$finpub = date($_POST['finpub']);
I just save the day, I think because the format is like 00/00/0000 so the / is "cutting" the value because I can just save int. in the database as you can see in the format I need, I just need numbers.
Really lost on this, sorry if this is a fool question.
I'm studying so don't be so hard.
EDIT:
Ok this is my code now I'm using mktime()
$iniciodate = str_replace("/",",",$_POST['iniciopub']);
$iniciopub = mktime(0,0,0,$iniciodate);
$findate = str_replace("/",",",$_POST['finpub']);
$finpub = mktime(0,0,0,$findate);
This saves this to timestamps for 10/27/2013 = 1382824800 but the same for 10/31/2013
Also I'm using this format, I have not problem with it
dateFormat: 'mm/dd/yy',
This is now set in datepicker jQuery UI

Your variable $iniciopub has value 1970-01-01 because strtotime() returned false:
var_dump( strtotime($_POST['iniciopub']) );
Take a look at supported date and time formats. If you are saying that you have format like 00/00/0000 in $_POST, then strtotime asumes this is american month, day and year (mm/dd/yyyy), like it states here.
If inputed format 00/00/0000 is dd/mm/yyyy then the easiest method would be to use DateTime::createFromFormat or str_replace('/', '-', 'dd/mm/yyyy'); to make it european date format dd-mm-yyyy.
Question update
This code is just wrong:
$iniciodate = str_replace("/",",",$_POST['iniciopub']);
$iniciopub = mktime(0,0,0,$iniciodate);
mktime() has 6 parameters (7th is is_dst wthich doesn't matter now). You cannot use $iniciodate like that, because you are inputing only 4th parameter into mktime() function, and not 4th, 5th and 6th as you might think.
mktime(0,0,0,'10,27,2013'); is not the same as mktime(0,0,0,10,27,2013); or `mktime(0,0,0,'10','27','2013');. The reason why date 10/27/2013 and 10/31/2013 return same timestamp is because in both cases, when you cast string 10,27,2013 and 10,31,2013 to integer (4th parameter), you get 10. See:
$v = '10,27,2013'; var_dump( (int)$v ); # int(10)
$v = '10,31,2013'; var_dump( (int)$v ); # int(10)
And because of that, your call is the same if you would call mktime() like:
var_dump( mktime(0,0,0,10) ); # int(1382832000)
If you would have error_reporting on (put error_reporting(-1); on the beggining of the php file), you would see, that after calling mktime(0,0,0,$iniciodate) you would get NOTICE:
Notice: A non well formed numeric value encountered in file.php on line XX
Since 10/27/2013 and 10/31/2013 are standard american date formats, you can just use strtotime() instead of mktime() to convert date to timestamps:
var_dump( strtotime('10/27/2013') ); # int(1382832000)
var_dump( strtotime('10/31/2013') ); # int(1383177600)
You asked in the comments: if i store a date as dd-mm-yyyy. how can i compare the date with other date. am i doing fine storing as timestamp?
Yes, you can store them as timestamp. But I haven't used timestamp in my code for ages, I am storing dates as YYYY-MM-DD; in RDBMS this is kinda best practice.

Better way not conver to mktime in PHP - save data as mktime already:
function mdf_init_calendars() {
jQuery(".mdf_calendar").datepicker(
{
showWeek: true,
firstDay: 1,
changeMonth: true,
changeYear: true,
showButtonPanel: true,
onSelect: function(dateText, self) {
var date = new Date(parseInt(self.currentYear, 10), parseInt(self.currentMonth, 10), parseInt(self.currentDay, 10), 23, 59, 59);
var mktime = (date.getTime() / 1000);
jQuery(this).prev('input[type=hidden]').val(mktime);
}
}
);
jQuery(".mdf_calendar").datepicker("option", "dateFormat", 'dd-mm-yy');
jQuery(".mdf_calendar").datepicker("option", "showAnim", 'fadeIn');
//+++
jQuery(".mdf_calendar").each(function() {
var mktime=jQuery(this).prev('input[type=hidden]').val();
var date = new Date(mktime*1000);
jQuery(this).datepicker('setDate', new Date(date));
});
}
You saves data in hidden inputs, and load in them when page loading, so in PHP code you get mktime always and do not need to think about data format, you can set it in js as you want (in example inline)
PHP:

Related

Highcharts with date and time for x axis (from a database with format YYYYMMDDHHMM)

I am trying to draw a graph using Highcharts for values with time and date for x axis. My database has the date values as YYYYMMDDHHMM (201409011345) and I want to plot y values with this date and time. my code is as follows ;
<?php
while ($row = mysql_fetch_array($result)) {
extract $row;
$data[] = "[$datetime, $value]"; //here $datetime is like 201405242625 (YYYYMMDDHHMM)
}
?>
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
series: [{
data: [<?php echo join($data, ',') ?>]
}]
});
Please give me any suggestions to get the correct datetime values for x axis
Thanks
Your date value needs to either be in epoch format, or a Date.UTC object.
I'm not sure how well PHP will understand your date format, but assuming that it can, you can use the strtotime() function.
In you case, it would be
$date_stamp = strtotime($datetime) * 1000
You need the * 1000 because PHP uses epoch time in seconds, Javascript uses milliseconds.
If PHP has a hard time interpreting your date format, you may need to format it within your database query, or use PHP's substr() function to break it up into its components and rebuild a readable date format.
References:
http://www.epochconverter.com/
http://php.net/manual/en/function.strtotime.php
How to list dates (day-by-day) on xAxis using HighCharts

Php crop time from date time string

I have a datetime string which I would like to crop the 'time' part out of.
I need to do some calculation on it so I need to convert it to Unix time stamp.
What I've tried:
Use substr, and then strtotime, but when checking the result back to a human readable time format, it is not the same as the original date.
function convert($dbTime){
$createDate = new DateTime($dbTime);
$strip = $createDate->format('Y-m-d');
$yearMonthDateArray = explode("-", $strip);
}
The explode here crashes.
Edit:
This is the value of dbTime: "2014-07-27 12:06:00"
I want it to be "2014-07-27", and then have strototime on this format. This does not work. Converting it back to human readable date it generates 2014-07-06
Regarding comments:
I have tried all sorts of datetime functions. They either crash or they don't return the proper time
Explode crashes - it doesn't continue to the next line of code.
Edit2:
This is what's going on next. This returns false
$timeWithMakeTime = mktime(0,0,0,(int)$yearMonthDateArray[0], (int)$yearMonthDateArray[1],(int)$yearMonthDateArray[2]);
Discarding all your messy code, I assume you just want this:
$dbTime = '2014-07-27 12:06:00';
$date = new DateTime($dbTime);
$date->setTime(0, 0, 0);
echo $date->getTimestamp();
DateTime is an object, so what if you want to get timestamp you can do is as follows:
function convert($dbTime){
$createDate = new DateTime($dbTime);
return $createDate->getTimestamp();
}
You can read more about getTimestamp and other DateTime functions
Make sure your variable $dbTime is in correct format. For example DateTime does not support split seconds.
$date = date('H:i:s', strtotime($dbTime));
echo $date;

How to return ISO date format in PHP for MongoDB?

I want to store the current date generated from PHP into MongoDB collection as an ISO date formate.
ISODate("2012-11-02T08:40:12.569Z")
However I am not able to generate such Kind of date in php which will be stored in MongoDB as an ISODate format.
This is what I ve done.
$d = new MongoDate(time());
echo $d;
and it is outputting something like,
0.00000000 1353305590
which is not the format I need. How to do this?
You could run the __toString function, or use the sec field
__toString will return a timestamp in usecs, which you can pass to date() after separating the seconds from milliseconds - read here: http://us1.php.net/manual/en/mongodate.tostring.php
OR, I personally prefer to have mongodb return just the seconds, which can be plugged directly into date() - read here: http://php.net/manual/en/class.mongodate.php
Also, if you're generating a MongoDate() for right now, you don't need to specify time();
In order to return an isodate, you need to do this:
echo date(DATE_ISO8601, (new MongoDate())->sec);
...
$exampleDate = new MongoDate();
echo date(DATE_ISO8601, $exampleDate->sec);
EDIT: To save your ISO date, you need to do the following:
$mongoDateObject = new MongoDate(strtotime("2012-11-02T08:40:12.569Z"));
For clarity, let's consider the following use case:
You need to convert a string in the simplified extended ISO 8601 format (e.g. returned by Javascript's Date.prototype.toISOString()) to and from PHP's MongoDate object, while preserving maximum precision during conversion.
In this format, the string is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ. The timezone is always zero UTC offset, as denoted by the suffix Z.
To keep milliseconds, we'll have to leverage PHP's DateTime object.
From string to MongoDate:
$stringDt = "2015-10-07T14:28:41.545Z";
Method 1 (using date_create_from_format):
$phpDt = date_create_from_format('Y-m-d\TH:i:s.uP', $stringDt);
$MongoDt = new \MongoDate($phpDt->getTimestamp(), $phpDt->format('u'));
Method 2 (using strtotime):
$MongoDt= new \MongoDate(strtotime ($stringDt),
1000*intval(substr($stringDt, -4, 3)) // cut msec portion, convert msec to usec
);
From MongoDate to string:
$MongoDt = new \MongoDate(); // let's take now for example
$stringDt =
substr(
(new \DateTime())
->setTimestamp($MongoDt->sec)
->setTimeZone(new \DateTimeZone('UTC'))
->format(\DateTime::ISO8601),
0, -5) // taking the beginning of DateTime::ISO8601-formatted string
.sprintf('.%03dZ', $MongoDt->usec / 1000); // adding msec portion, converting usec to msec
Hope this helps.
convert ISO date time in UTC date time here :
$timestamp = $quicky_created_date->__toString(); //ISO DATE Return form mongo database
$utcdatetime = new MongoDB\BSON\UTCDateTime($timestamp);
$datetime = $utcdatetime->toDateTime();
$time=$datetime->format(DATE_RSS);
$dateInUTC=$time;
$time = strtotime($dateInUTC.' UTC');
$dateInLocal = date("d M Y", $time);
echo $dateInLocal; die;
You can convert ISODate time by using below code.
* return ISO-8601 date format:YYYY-MM-DD'T'HH:mm:ss.sssXXX , for example: 2015-09-07T10:13:45.110-07:00 .
*/
date("Y-m-d\TH:i:s.000P", strtotime($date));

PHP: How to compare a time string with date('H:i')?

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 ...
}

How should I store a date in PHP for use with javascript?

What I want to do is make a script on the server read a text file, sort it, then output it to a javascript object (probably via JSON). The text file in question looks something like this:
13/09/2009,17/09/2009,Arbitrary dates
14/09/2009,18/09/2009,Some random comment
14/09/2010,18/12/2010,A comment to the dates
14/09/2010,18/09/2010,A subset of another date
14/09/2001,18/09/2002,The oldest date
The php to handle the filereading looks like this:
function loadDates()
{
$dateFile = fopen("dates.txt", "rt");
$dates = array();
if($dateFile)
{
flock($dateFile,LOCK_SH);
$i = 0;
while(!feof($dateFile))
{
$text = fgets($dateFile);
if($text !== FALSE)
{
$i++;
$arr = explode(",",$text,3);
//actual storage
$dates[$i]['start'] = strtotime($arr[0]);
$dates[$i]['end'] = strtotime($arr[1]);
$dates[$i]['comment'] = $arr[2];
}
}
fclose($dateFile);
//sort by start date, then by end date
foreach($dates as $key => $item)
{
$start[$key] = $item['start'];
$end[$key] = $item['end'];
}
array_multisort($start, SORT_ASC, $end, SORT_ASC, $dates);
return $dates;
}
else
{
return FALSE;
}
}
However, that stores unix timesstamps in the start and end dates. I would use the DateTime class, but I'm currently restricted to PHP 4.4. Ideally, I'd like to store the dates in a format that:
Can be compared numerically
Are human readable (allowing human editing of dates.txt)
Are consistently formatted (ie "01-01-1900" is converted to "01/01/1900")
Can be converted to a javascript Date object
How would I go about storing the dates so they satify these restrictions?
The safest is to use UNIX timestamps
in javascript, you can use
var mydate = new Date();
mydate.getTime(); //timestamp
mydate.setTime(your_timestamp); //set using timestamp
in php the date function takes the timestamp as second parameter.
see http://jp.php.net/manual/en/function.date.php
and https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Date
EDIT:
Also see strftime http://jp.php.net/manual/en/function.strftime.php
EDIT:
Note: the javascript function takes milliseconds, and the php functions use seconds. divide the output of the javascript by 1000 or use something like the following:
Date.prototype.getTimeInSeconds = function() {
return this.getTime()/1000;
}
var mydate = new Date();
mydate.getTimeInSeconds(); //PHP-compatible timestamp
Store the dates thus:
19991231 = Dec. 31, 1999
20000704 = July 4, 2000
Human readable, definitely sortable, and you can make a JavaScript function for the conversion.
I will provide you with a hack from my deranged mind:
(this assumes that x is that date in yyyymmdd form)
new Date((x-(x%10000))%9999,(((x%10000)-(x%100))%99)-1,x%100)

Categories