I'm using the datetimepicker jquery plugin and have the following code to display it:
var dateToday = new Date();
$('#post_date_picker').datetimepicker({
minDate: dateToday,
timeFormat: 'hh:mm p z',
timezoneList: [
{ value: -300, label: 'Eastern'},
{ value: -360, label: 'Central' },
{ value: -420, label: 'Mountain' },
{ value: -480, label: 'Pacific' }
]
});
Since I'm displaying it in 12 hour format instead of 24 and using the min date if the server time is already PM I can select the time and it outputs it like 05/27/2015 08:50 p -0500
I then do the following code to get the date ready to be inserted into the database:
$date_time = strtotime($_POST['post_date']);
$post_date = date('Y-m-d H:i:s', $date_time);
The problem is strtotime isn't recongining the p for PM and is inserting the date basically 12 hours previously. How can I do this?
Set timeFormat: 'hh:mm tt z'.
And in php use date_create & date_format ( $date_time,'Y-m-d h:i:sA')
See the difference between( strtotime / date_create ).
// method using date_create
//$date=$_POST['post_date'];
$date='05/27/2015 08:50 p -0500';
$date_time=date_create($date);
$post_date=date_format($date_time,'Y-m-d H:i:s');
echo $post_date."<br>";//outputs 2015-05-27 08:50:00
//method using strtotime
$date_time = strtotime($date);
$post_date = date('Y-m-d H:i:s', $date_time);
echo $post_date;//outputs 2015-05-27 13:50:00
strtotime can take many string parameters, may be when you pass the date as '05/27/2015 08:50 p -0500' some conflict is occurring resulting in wrong interpretation of time.
Related
I have a MySQL DB table with a column named "timestamp", a type of timestamp, and attribute of on update CURRENT_TIMESTAMP and a default of CURRENT_TIMESTAMP.
If I add a record to the table, specifying other values, but not the timestamp, then the timestamp is automatically added like 2016-12-28 17:02:26.
In PHP I query the table using the following query
SELECT * FROM history WHERE user_id = 9 ORDER BY timestamp ASC
The result of the query is saved into $rows and I use a foreach to create an array with some of the other values formatted. I am attempting to format the time stamp to UK type 24-hour date time: dd/mm/yy, HH:MM:SS.
I have tried both the date() and strftime() functions as follows:
$formatted_datetime = strftime("%d %m %y %H %M %S", $row["timestamp"]);
$formatted_datetime = date("d/m/y, H:i:s", $row["timestamp"]);
Both of these result in the following notice and the date time being output incorrectly like 01 01 70 00 33 36:
Notice: A non well formed numeric value encountered in /home/ubuntu/workspace/pset7/public/history.php on line 20
I am new to PHP and MySQL and so far none of the other questions or documentation I have seen have successfully addressed performing this conversion.I do not understand why strftime() does not work, nor how to do this properly?
To do this the OO (and most flexible) way use DateTime class and use the static createFromFormat method to instantiate a new DateTime object:
$new_datetime = DateTime::createFromFormat ( "Y-m-d H:i:s", $row["timestamp"] );
Now you can use the $new_datetime object to generate any string representation you'd like by calling the object's format method:
echo $new_datetime->format('d/m/y, H:i:s');
To boot, you since you've a DateTime object you can now also to any manner of transformation (like shifting timezones or adding days), comparison (greater or less than another DateTime), and various time calculations (how many days/months/etc... between this and another DateTime).
DateTime:http://php.net/manual/en/class.datetime.php
Learn it. Love it. Live it.
Normally in MySQL date timestamp save time as YYYY-MM-DD HH:MM:SS (2016-12-20 18:36:14) formate you can easily convert them as your wish using date formate but have to convert your input to time first. Following will do the trick
$formatted_datetime = date("d/m/y, H:i:s", strtotime($row["timestamp"]));
Why not make MySQL do the work? And do you really want mm/dd/yy, not dd/mm/yy?
SELECT *, DATE_FORMAT(timestamp, '%m/%d/%y, %T') formatted_date FROM ....
Then you can extract the formatted date as $row['formatted_date'].
See https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
The date is of timestamp type which has the following format: ‘YYYY-MM-DD HH:MM:SS’ or ‘2008-10-05 21:34:02.’
$res = mysql_query("SELECT date FROM times;");
while ( $row = mysql_fetch_array($res) ) {
echo $row['date'] . "
";
}
The PHP strtotime function parses the MySQL timestamp into a Unix timestamp which can be utilized for further parsing or formatting in the PHP date function.
Here are some other sample date output formats that may be of practical use:
echo date("F j, Y g:i a", strtotime($row["date"])); // October 5, 2008 9:34 pm
echo date("m.d.y", strtotime($row["date"])); // 10.05.08
echo date("j, n, Y", strtotime($row["date"])); // 5, 10, 2008
echo date("Ymd", strtotime($row["date"])); // 20081005
echo date('\i\t \i\s \t\h\e jS \d\a\y.', strtotime($row["date"])); // It is the 5th day.
echo date("D M j G:i:s T Y", strtotime($row["date"])); // Sun Oct 5 21:34:02 PST 2008
I would use the Carbon class and its String Formatting
$carbon = Carbon::instance('2016-12-28 17:02:26');
Then you can format it the way you want.
I have this question:
I have selected date & time from the table & echoed them just fine but I don't like the date & time format that is echoed. Here in Central-Southern Africa, we are used to 24hrs (like 16:30hrs instead of 4:30pm etc).
Here is the code:
("SELECT * FROM me order by 1 DESC LIMIT 0,10");
$date = $run_post['date'];
$time = $run_post['time'];
And them I do this:
echo $date;
and it gives me 2015-11-13 but I want 13th November 2015
and then
echo $time;
giving me 2015-11-13 12:53:43 but want like 16:30:00 hrs format.
Finally, I also want to echo my (UTC+02:00) Cairo Time zone. Currently it is giving me -2hrs
You should use the DateTime Class as you can set the timezone in it.
Example with Timezone Europe/London:
$date = new DateTime('2015-11-13 12:53:43', new DateTimeZone('Europe/London'));
echo $date->format('d\t\h F Y') . "\n";
echo $date->format('H:i:s') . 'hrs';
How to add Timezone to DateTime
I'm assuming that your default time zone is set to UTC. If you want to display time as per your time zone(UTC+02:00), then you can do something like this:
function display_time($time){
$unixdatetime = strtotime($time) + 7200;
return strftime("%d %B %Y, %H:%M %p",$unixdatetime);
}
And when you call this display_time function, for example,
echo display_time($run_post['time']);
then it would display,
13 November 2015, 14:53 PM
format method of DateTime class is what you need.
$date = new DateTime($run_post['time']);
echo $date->format('d\t\h\,F Y');
Will echo something like 13th, November 2015)
You have the documentation of how to format in
https://secure.php.net/manual/en/function.date.php
I know this question has been asked many times as I have found a few on google and also on stackoverflow.
but none of them explained how to format my datetime in my php so it works in combination with jquery countdown timer. so I am going to ask it here in a hope i get someone shed a light on this for me.
Basically what i am trying to do is to create a countdown timer which will work with mysql datetime.
the datetime is stored in mysql so All need to do is to get the correct format in my php so the countdown timer could work with it.
I am using this plugin: http://keith-wood.name/countdown.html
and here is what i have so far:
PHP formatting:
$end_date = date("m d Y H:i:s T", strtotime($row["end_date"]));
Jquery/Javascript code:
<script type="text/javascript">
$(function(){
var countdown = $('#countdown'),
ts = new Date(<?php echo $end_date * 1000; ?>),
finished = true;
if((new Date()) > ts)
{
finished = false;
}
$('#defaultCountdown').countdown({
timestamp : ts,
callback : function(days, hours, minutes, seconds)
{
var message = "";
message += days + " days, ";
message += hours + " hours, ";
message += minutes + " minutes, ";
message += seconds + " seconds ";
message = (finished ? "Countdown finished" : "left untill the New Year");
countdown.html(message);
}
});
});
</script>
when i run this code, all i get is 0 hours, 0 minutes, 0 seconds.
I can only suspect that the issue is from formatting the datetime in my php section!
or am i missing something else as well?
okay I have managed to minify the code to this:
<script type="text/javascript">
$(document).ready(function () {
$('#defaultCountdown').countdown({
until: new Date(<?php echo $end_date; ?>),
compact: true
});
});
</script>
and changed the php to this:
$end_date = date("Y, n, j, G, i, s", strtotime($row["end_date"]));
However, the time shown in the coutdown timer is wrong (way off).
the $end_date is: September 22 2013 23:30:00 GMT in mysql datetime
but the jquery countdown timer is showing:
34d 06:21:48
2013, 9, 22, 23, 30, 00
34days and 6 hours blah blah is absolutely wrong!
what am i doing wrong here now?
The JavaScript Date object is constructed as follows:
Date(year, month, day, hours, minutes, seconds, milliseconds)
That means you probably should be doing something along these lines:
$end_date = date("Y, n, j, G, i, s", strtotime($row["end_date"]));
Sources:
JavaScript Date-object
PHP date-function
EDIT:
In addition, I seem to have found the problem in the jQuery Countdown manual:
A note on Date - the JavaScript Date constructor expects the year,
month, and day as parameters. However, the month ranges from 0 to 11.
To make explicit what date is intended (does a month of 3 mean March
or April?) I specify the month from 1 to 12 and manually subtract the
1. Thus the following denotes 25 December, 2010.
So, you'd have to split the string, substract 1 from the month and rebuild...
$tmp_date = explode(', ', $end_date);
$tmp_date[1] = $tmp_date[1] - 1;
$end_date = implode(', ', $tmp_date);
Link to jsFiddle
Im using JQuery Full Calendar Plugin. Code:
$('#mycalendar').fullCalendar({
** options **
events: function(start, end, callback) {
$.ajax({
url: '/myloader/',
dataType: 'json',
data: {
// our hypothetical feed requires UNIX timestamps
start: Math.round(start.getTime() / 1000),
end: Math.round(end.getTime() / 1000)
}
*** more stuff
});
now on myloader php side when i try to get start and end dates here is what i get:
var_dump(date('m/d/Y H:i:s', $_GET['start']), date('m/d/Y H:i:s', $_GET['end']));
this returns:
string(19) "01/27/2013 06:00:00"
string(19) "03/10/2013 06:00:00"
why is it 6:00:00 ? i want it to be 00:00:00 for start and 23:59:59 for end
I know i can hack through it using PHP but is there a reason why full calendar returns such date?
If i use PHP i can get desired results using:
$start = strtotime(date('m/d/Y', $start) . ' 00:00:00');
$end = strtotime(date('m/d/Y', $end) . ' 23:59:59');
but i dont want to do it on PHP side is there a way full calendar to give correct time?
If its a timezone issue how can it be fixed?
thanks
How about this:
var_dump(
date('m/d/Y H:i:s', strtotime(date("m/d/Y",(int)$_GET['start'])),
date('m/d/Y H:i:s', strtotime(date("m/d/Y",(int)$_GET['end']))
);
I am working on task in which dates are involved. I have a person's age in months+days. Now I want to get a date when this person reach to a specific age in months.
For example:
A person is 250 months and 15 days old on 2010-1-25.
On which date this person will become 300 months old?
Function Signature may be:
function getReqDate( $startDate, $currAgeMonths, $currAgeDays, $reqAgeMonths ) {
//return date
}
Since you calculate the current age from the birthdate, I suggest you also use the birthdate instead of the current age to calculate when a user gets 300 months old. The following is the equivalent of the DateTime solution given above (does not require 5.3):
echo date('r', strtotime('+300 months', strtotime('1990-10-13')));
With the second param being the birthdate timestamp the above would give
Tue, 13 Oct 2015 00:00:00 +0200
Further reading:
http://us2.php.net/manual/en/function.strtotime.php
http://www.rafaeldohms.com.br/2006/09/15/strtotime-is-it-useful/en/
$date = new DateTime('1990-10-13');
$date->add(new DateInterval('P300M'));
echo $date->format('r');
See DateInterval to see how you write the interval. Again, PHP 5.3.0+ required.
Use the php strtotime function you can get the date you are looking for. e.g.
strtotime('+50 months', mktime());
function getReqDate( $startDate, $currAgeMonths, $currAgeDays, $reqAgeMonths ) {
$unixStartDate = strtotime($startDate);
$dateBirth = strtotime("-$currAgeDays months", strtotime("-$currAgeMonths months", $unixStartDate));
return strtotime("+$reqAgeMonths months", $dateBirth);
}
function getReqDate($startDate, $reqAgeMonths ) {
list($year,$month,$day) = explode('-',$startDate);
$date = date("Y-m-d", mktime(12, 0, 0, $month+$reqAgeMonths, $day, $year ));
return $date
}