i have an option value for time in main form and another option for am or pm...now what confuses me is how am i going to code it when if example i choese 1 and then pm...how am i goin to call it on the database?i also have to filter the sales reports by time and by pm.. hope someone can help me..thanks
You can set AM/PM through capital A or lowercase a depending on your preference of capital AM/PM or lowercase am/pm. As far as your question on how to interact with the database, your time inserted should be unedited, IE you don't want to apply the styling from the date function and insert that into your database as a string because that will prevent you from changing it in the future. Instead create a DATETIME or TIMESTAMP column in your table, and put the date in that, then when you select from the table you can apply styling to fit your needs.
http://dev.mysql.com/doc/refman/5.0/en/datetime.html
http://www.php.net/manual/en/function.date.php
From Database to Display
The PHP Function [date()][1] can be used to convert a Unix Timestamp into a Human-Readable form.
<?php
// $time is assumed as a Timestamp from DB or other
echo date( 'g:i:sa, l jS F Y' , $time );
?>
Will Return
3:43pm, Wednesday 25th August 2010
Alternately, you could use the [strftime()][2] which performs a similar role, but has different placeholders (it also lacks the placeholder for "st","nd","th" after the day number). The benefit of this function is that you could include plain text within the format, as all placeholders are prefixed with "%" - so "hello" would not be treated as a placeholder.
<?php
// $time is assumed as a Timestamp from DB or other
echo strftime( '%l:%M:$S%P, %A %e %B %Y' , $time );
?>
Will Return
3:43pm, Wednesday 25 August 2010
Translating User-Entered Data into a Format for the Database
Most databases I have worked with have been pretty intelligent about how they handle timestamps. All you should need to do is, if there are more than one field being used (ie one for hour, one for minutes, one for am/pm), join them together into a single string, and just make sure that the resulting string is of a format able to be parsed by PHP.
The function strtotime() can turn a Human-readable time into a Unix Timestamp, which your database should be able to handle without any problems.
<?php
// $input is the string (joined or solo) containing the Human-readable timestamp
$input = "2010/08/25 3:43pm";
if( ( $out = strtotime( $input ) )===false ){
echo 'Timestamp "'.$input.'" Unrecognisable';
}else{
echo $out;
}
?>
Will Return
1282743780
If the string being parsed is not recognisable according to the PHP Date Time Formats, then it will return false.
Related
I am using MsSQL in PHP. I am storing the time in database table row with datetime as datatype.The time is stored like this :08:30:00.0000000.I need the time to be displayed in 08:30.I have used
date('h:i', $time_value); // $time_value stores the time value
This formats the date and gives the result in 4:00. Any formatting is required to display the correct time stored in database?
The PHP date function does not expect a Mysql datetime as second parameter but you do so:
date('h:i', $time_value);
^
|
second parameter
This is the reason why it does not work. You're using the wrong value, convert the database value into a timestamp first because the date function needs a timestamp. As you migh imagine, this has been done before, here is just a selection of related Q&A material:
MySQL convert datetime to unixtime?
MySQL convert datetime to Unix timestamp
Alternatively just use a string function like substr to obtain the string you're looking for:
$time_value = '08:30:00.0000000';
echo substr($time_value, 0, 5); # 08:30
Demo: https://eval.in/146148
You can do the conversion / formatting with the SQL statement already, a related example is given in:
How to display time in HH:MM format?
You can also use:
date('h:i', strtotime('08:30:00.0000000'));
In your case:
date('h:i', strtotime($time_value));
I'm doing a date search filter where I have my date displayed as "j.n.Y G:i (26.6.2012 15:22)".
A user can enter the whole date or only a portion of it: "26.6","6.2012","6","15:22" are all valid inputs. Because I need to check this date in the database the format needs to be changed to the one of the database. For that I use:
$datum = '25.6.2012';
$date = DateTime::createFromFormat('j.n.Y',$datum);
echo $date->format('Y-m-d H:i');
Where I get an error if $datum is not in the format j.n.Y (if I only enter j.n or one of the above mentioned string portions i get an error).
A problem is also, for the entered string 'j.n.Y', i get the right output of the date, which also has the current time added to the date string (which was not in the initial date string). Example: I enter "22.6.2012", then I get the output "2012-06-22 15:33".
Can these two problems get fixed with existing php functions or should I make my own?
Help would be greatly appreciated.
You can list your acceptable data formats in an array, and loop around DateTime::createFromFormat() to see if any of the inputs produce an acceptable date:
$formats = array( 'j.n', 'j.n.Y');
$datum = '25.6.2012'; $date = false;
foreach( $formats as $format) {
$date = DateTime::createFromFormat( $format, $datum);
if( !($date === false)) break;
}
if( $date === false) {
echo "Invalid date!\n";
}
Finally, if you want to get rid of the current time in the newly created object and set the time to 00:00:00, just use the setTime() method on the date object:
// Sets the time to O hours, 0 minutes, 0 seconds
$date->setTime( 0, 0, 0);
For the first problem, you will need to write some code of your own because some of your acceptable inputs are not among the recognized input formats. Normalizing the input value will require you to fully parse it (a regular expression is a good way to start), and then you can call DateTime::createFromFormat without trouble.
For the second problem, putting an exclamation mark ! at the beginning of your format string would fix the time issue. From the documentation:
If format contains the character !, then portions of the generated
time not provided in format, as well as values to the left-hand side
of the !, will be set to corresponding values from the Unix epoch.
The Unix epoch is 1970-01-01 00:00:00 UTC.
However, since you are going to need to fully parse the input as mentioned above the matter is moot. Also note that the exclamation mark would cause missing values for year, month and day to use defaults that are probably undesirable.
Not sure whats up with the code
$date = strtotime("%b %d, %Y", $datedata);
$time = strtotime("%I:%M:%S %p", $datedata);
The time i gets from the DB is 1298747601 and is the $datedata
I have date_default_timezone_set('America/Los_Angeles'); at the top of the script.
Use strftime() or date(), not strtotime(). Strtotime is meant to format textual dates, not timestamps.
It's better to use the DATETIME datatype in your database instead of an int containing a timestamp. Using a DATETIME means easier calculating with dates and you can format the date directly in your query.
strtotime() is for converting a string to a time like, $timestamp = strtotime("1:33 PM EST Next Friday");.
You want date(), which takes a format string and a timestamp to create a formatted date time string, and uses the current time (from time()) if no timestamp is passed, like date("h:i:s A T, M jS, Y", $timestamp) which would output something like "1:33:00 PM EST, March 4th, 2011". Also, note that if you want to do words in the format, like "23rd of January", and the letters in the words are also date formatting characters, in this case the 'o' in 'of' is the ISO-8601 year number formatting option, you must escape it with a \ slash like "jS \of F". As the f is not a formatting option, it does not need to be escaped, but if it did, then it would be "\o\f"
There's also a DateTime object that's built into more recent PHP versions that you can look into.
I disagree with Ray that it is better to store a DateTime datatype in SQL rather than an integer timestamp. They're about the same. You can still search for date ranges in the DB simply by finding numbers greater than X timestamp and less than Y timestamp, and, as a plus, everything that you get from the DB is already in a timestamp format that can be used easily by PHP without having to convert it to a proper timestamp.
My web application consists of library type system where books have due dates.
I have the current date displayed on my page, simply by using this:
date_default_timezone_set('Europe/London');
$date = date;
print $date("d/m/Y");
I have set 'date' as a variable because I'm not sure if it makes a difference when I use it in the IF statement you're about see, on my library books page.
On this page, I am simply outputting the due dates of the books, many have dates which have not yet reached todays date, and others which have dates greater than todays date.
Basically, all I want is the due date to appear bold (or strong), if it has passed todays date (the system displayed date). This is what I have and thought would work:
<?
if ($duedate < $date) {
echo '<td><strong>';
} else {
echo '<td>';
} ?>
<?php echo $date('d/m/Y', $timestamp);?></strong></td>
I have declared $timestamp as a var which converts the date of default MySQL format to a UK version. Can anyone help me out? I thought this would've been very straight forward!
try:
if (strtotime($duedate) < time()) {
// oooh, your book is late!
}
Instead of working with the formatted dates, work with their timestamps. Either convert them back with strtotime() or use time() instead of date. Timestamps can be compared like regular numbers, because that's what they just are.
Okay :) Let's start here:
$date = date; // Wrong!
print $date("d/m/Y");
The above only works because PHP thinks date is a constant. But since you didnt set this constant PHP will convert it to the string 'date'. So $date contains 'date'. Then, when calling $date() as a function, PHP evaluates $date's content, which is 'date' and uses that as the function name, e.g. date(). What you really wanted to do was just $date = date('d/m/y').
Here is how date works:
string date ( string $format [, int $timestamp ] )
First argument is the desired output format, the second argument is an optional timestamp for which the output will be generated. If omitted it will be now. The function returns the output as string.
I assume your $duedates are already formatted strings, e.g. 2010-04-06. So when you do $duedate < $date, you are really doing a string comparison, because both variables hold formatted strings, but not timestamps.
Timestamps on the other hand are just numbers. A timestamp is the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). You can get the timestamp for the current date and time with the function time() and you can convert strings that represent dates with strtotime(). So when you want to compare your dates, do
if ( strtotime($duedate) < time() ) { // ... do something
And that's really all there is to it.
I am trying to display a time I have in my database. I managed to have it display a time in the correct format for what I need, but for some reason, it is only displaying '4:00' every time.
Here is my code:
date('g:i', strtotime($row['startTime']))
An example of I have the time displayed in my database is like this: 00:12:30
Why is it showing '4:00' every time?
strtotime expects a datetime format ... you should do
date('g:i', strtotime('01 January 2009 ' . $row['startTime']))
Whats the underlying database, and what datatype does the startTime column have? Peering at the closest php code I have, strtoime works fine with a DATETIME representation in the DB (MySQL).
strtotime converts a date time string to a Unix timestamp.
Perhaps your $row['startTime'] doesn't qualify as a date time string.
None of the examples here discussed a date time string which did not include a date.
The link also said that if strtotime is confused, it returns random results. I would add a few more format characters and see what else is returned.
As noted the problem is the use of strtotime(). The following works on my machine, if it's of any use:
$date_text = $row['startTime']; // assuming the format "00:12:30"
list($hrs,$mins,$secs) = explode(":",$date_text); // in response to the question in the comments
/* the explode() takes the string "00:12:30" and breaks into three components "00","12" and "30".
these components are named, by their order in the array formed by explode(), as $hrs, $mins and $secs.
see: http://us3.php.net/manual/en/function.explode.php
and: http://us3.php.net/manual/en/function.list.php
*/
echo "<p>" . date("g:i",mktime($hrs,$mins,$secs)) . "</p>";