473,583 Members | 3,386 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Convert User entered date and time to Unix Timestamp before inserting to database

How do you convert a user inputted date to a unix timestamp before
insterting it into your database? I have a form, with a textfield for
a date that the user inputs in the format mm-dd-yyyy and three dropdow
boxes for hours, minutes, and AM/PM. All of these need to be considered
together and converted to one Unix Timestamp and then inserted to the
MYSQL date field. The type of field is INT (11) so that I can instead
of the standard 0000-00-00 format of MYSQL so that I can do better
calculations and queries. How can this be accomplished?

Thanks.

Jul 17 '05 #1
13 9281
Here's some code to illustrate my question. I changed the dropdown
boxes to input boxes to make it shorter to post, but the concept is the
same...

<?php require_once('C onnections/con_date.php'); ?>
<?php
mysql_select_db ($database_con_ date, $con_date);
$query_rs_date = "SELECT * FROM date_time";
$rs_date = mysql_query($qu ery_rs_date, $con_date) or
die(mysql_error ());
$row_rs_date = mysql_fetch_ass oc($rs_date);
$totalRows_rs_d ate = mysql_num_rows( $rs_date);
?>

<body>
<form action="" method="post" name="date_form " id="date_form" >
<p>Date:
<input name="date" type="text" id="date">
</p>
<p>Hour:

<input name="hour" type="text" id="hour" size="2" maxlength="2">
Minute:
<input name="minute" type="text" id="minute" size="2"
maxlength="2">
<select name="am_pm" id="am_pm">
<option value="0">AM</option>
<option value="1">PM</option>
</select>
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>
</body>
</html>
<?php
mysql_free_resu lt($rs_date);
?>

Jul 17 '05 #2
In article <11************ **********@c13g 2000cwb.googleg roups.com>, perplexed wrote:
How do you convert a user inputted date to a unix timestamp before
insterting it into your database? I have a form, with a textfield for
a date that the user inputs in the format mm-dd-yyyy and three dropdow
boxes for hours, minutes, and AM/PM. All of these need to be considered
together and converted to one Unix Timestamp and then inserted to the
MYSQL date field. The type of field is INT (11) so that I can instead
of the standard 0000-00-00 format of MYSQL so that I can do better
calculations and queries. How can this be accomplished?


here are some never-to-forget functions:

mysql: dateformat, from_unixtime, unixtime
php: strtotime

--
Met vriendelijke groeten,
Tim Van Wassenhove <http://www.timvw.info>
Jul 17 '05 #3
If you properly validated the date and time fields after user input,
you could then create a PHP timestamp by inserting the proper string
portions of the date into a PHP timestamp function. You would then
have a PHP timestamp for PHP purposes only.

For instance, below, you place the contents of your hour and minute
variable into the function as well as the proper relative string
sections of your date string using the substr function:

mktime($hour,$m inute,0,substr( $date,0,2),subs tr($date,3,2),s ubstr($date,6,4 ));

You now have a PHP timestamp, not a MYSQL timestamp.

Note that before you load the PHP timestamp function above, you would
adjust the hour variable for AM/PM in your edit function. For
instance, if your user entered 2AM, you would need to change the
variable to 14 prior to entering it in the PHP timestamp function.

You now have a PHP timestamp for whatever purposes you need it in PHP.
Why couldn't you then just load your database with the standard MYSQL
date timestamp 0000-00-00 00:00:00. You could always pull a range of
dates back out of your database and easily convert them back into PHP
timestamps, etc. or whatever else for complex calculations (PHP which
would be the best place to perform these calculations anyway). Again
using similar string manipulation techniques!

So just format the user input for entry into the database in the
standard timestamp field format 0000-00-00 00:00:00.

You just load a PHP variable as follows:

$temp_date =
substr($date,6, 4)."-".substr($date, 0,2)."-".substr($date, 2)."
".$hour.":"$min ute.":00";

and then put this in your database? Remember to have your edit
function put '0's' where they are required by your database! If March,
then the $temp_date would end up having '03' in the month section of
the string, so you have to analyze the user input in some sort of edit
function and translate the input as indicated.

The key to all this is your edit of the user data prior to entering it
in the database.

When you later call your data out of your database by a range of dates,
you could convert the MYSQL timestamps back into PHP timestamps, etc.
fairly easily, again, by manipulating the strings. Sometimes it seems
best to leave the database as just a repository with the proper data
types and to use PHP to manipulate the data once you have called it.
For instance, if you later pulled this out of the database: 2004-01-02
14:06:00 , it would be fairly straightforward getting this string back
into a PHP timestamp -
$variable= "2004-01-02 14:06:00";
$timestamp=mkti me(substr($vari able,11,2),subs tr($variable,14 ,2),substr($var iable,17,2),sub str($variable,8 ,2),subst($vari able,5,2),subst r($variable,0,4 ));

Apologies if I missed the mark, but I think its best in most situations
to let PHP be the middleman and keep the data standard?

I did a little of this in the past. Let me know if I this helps.
Scott

Jul 17 '05 #4
Scott,

Thank you. This is my first project with intensive date/time functions
in php/mysql. I was not sure which method to use php timestamps and
have a INT type data field or to use a MYSQL timestamp field. Now I
realize that MYSQL timestamp is the way to go. Now I just need to
figure out the best way to get the user to input the correct format,
validate it and then insert it to MYSQL. I will figure out the queries
to sort by date and convert from MYSQL timestamp to PHP timestamp
afterward.

Thanks for the help.
Chris

Jul 17 '05 #5
perplexed wrote:
Scott,

Thank you. This is my first project with intensive date/time functions
in php/mysql. I was not sure which method to use php timestamps and
have a INT type data field or to use a MYSQL timestamp field. Now I
realize that MYSQL timestamp is the way to go. Now I just need to
figure out the best way to get the user to input the correct format,
validate it and then insert it to MYSQL. I will figure out the queries
to sort by date and convert from MYSQL timestamp to PHP timestamp
afterward.

By the way, as far as MySQL column types go, I'd say you need a DATETIME
column and not a TIMESTAMP column: a TIMESTAMP column is automatically
updated by the database whenever the row is updated, and since you were
talking about storing a user-entered date and time that may not be what
you want.

But probably you were already aware of that.

JP

--
Sorry, <de*****@cauce. org> is een "spam trap".
E-mail adres is <jpk"at"akamail .com>, waarbij "at" = @.
Jul 17 '05 #6
I noticed that Message-ID:
<11************ **********@z14g 2000cwz.googleg roups.com> from perplexed
contained the following:
Thank you. This is my first project with intensive date/time functions
in php/mysql. I was not sure which method to use php timestamps and
have a INT type data field or to use a MYSQL timestamp field. Now I
realize that MYSQL timestamp is the way to go.


It is? I find UNIX timestamps easier if you don't have to deal with
dates before 1970. The only downside I can see is that you need php
functions to read them ie I can't read a date directly in phpMyadmin for
instance.

It all depends on the app.

--
Geoff Berrow (put thecat out to email)
It's only Usenet, no one dies.
My opinions, not the committee's, mine.
Simple RFDs http://www.ckdog.co.uk/rfdmaker/
Jul 17 '05 #7
.oO(scotty)
So just format the user input for entry into the database in the
standard timestamp field format 0000-00-00 00:00:00.

You just load a PHP variable as follows:

$temp_date =
substr($date,6 ,4)."-".substr($date, 0,2)."-".substr($date, 2)."
".$hour.":"$mi nute.":00";

and then put this in your database? Remember to have your edit
function put '0's' where they are required by your database!
sprintf() might come in handy to add leading zeros where necessary:

$temp_date = sprintf('%u-%02u-%02u %02u:%02u:00', ...);
For instance, if you later pulled this out of the database: 2004-01-02
14:06:00 , it would be fairly straightforward getting this string back
into a PHP timestamp -
$variable= "2004-01-02 14:06:00";
$timestamp=mkt ime(substr($var iable,11,2),sub str($variable,1 4,2),substr($va riable,17,2),su bstr($variable, 8,2),subst($var iable,5,2),subs tr($variable,0, 4));
Much too complicated, DATE_FORMAT() and UNIX_TIMESTAMP( ) exist in MySQL.
Apologies if I missed the mark, but I think its best in most situations
to let PHP be the middleman and keep the data standard?


Yep.

Micha
Jul 17 '05 #8
.oO(perplexed)
How do you convert a user inputted date to a unix timestamp before
insterting it into your database?


You don't. If you want to store dates in a database use a native date
type like DATETIME. MySQL offers tons of functions to work with dates.

Micha
Jul 17 '05 #9
.oO(perplexed)
Now I just need to
figure out the best way to get the user to input the correct format,
validate it and then insert it to MYSQL.


1) Split the user submitted string into its values. If you're sure the
format will always be like 'mm-dd-yyyy' you could try it with regular
expressions, sscanf() or explode():

$test = '12-13-2004';
sscanf($test, '%u-%u-%u', $month, $day, $year);

or

$values = explode('-', $test);

2) Validate the date. Use the values from above and checkdate() to see
if the entered date is valid.

3) Validate the time. Check that $hour is between 1 and 12, $minute
between 0 and 59 (don't omit this check even if you use a dropdown box
with just a few values). Then change from 12-hour time to 24-hour time
according to the am/pm setting.

4) Now you have all the values for date and time and can insert them
into the database.

HTH
Micha
Jul 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
32412
by: Ben | last post by:
I would like to use php to query a database and retrieve a unix timestamp. The problem is that mysql is storing the data in the date format and not a timestamp. I am sure that I can amend my query to format the date returned as a timestamp without having to do the conversion in php. Can someone tell me what to put in my db query?
3
1976
by: Hayden Kirk | last post by:
Ok This is really anoying me... I am using a timestamp colum in my MySQL table, I generate a timestamp with php using time(); When I pull the time from the table I get some date from the 1970's... does anyone know whats going on? Im using the date() function to display the timestamp. Thanks
1
71772
by: Sugapablo | last post by:
How do you convert a unix timestamp to date('Y-m-d H:i:s')?
3
2326
by: Ralf Meuser | last post by:
Hi there, I get form a database time with the format : 'Jan 01 1900 06:00PM' I want to convert it to :HH:MM I tryed it with $heure=(date("H:i",strtotime($row)) but I get allways 20:55. even when time changes. Whats wrong ? Does anybody know where I can get a good function which will convert date to
3
1481
by: Shelly | last post by:
Can anyone help? Here is what I have (part, at least) echo $dbResult . ' ' . $dbResult . ' ' . $dbResult . " " . date("M j, Y, g:i a", $dbResult) . '<br>'; Here is what it puts out (formatted here to make it easier for you to read)
3
10034
by: Bruno BAGUETTE | last post by:
Hello, I'm looking for a way to convert a unix timestamp to a PostgreSQL date without using ::abstime which seems to be deprecated. Currently, I do that query : levure=> select 1063147331.843::int4::abstime; abstime ------------------------
4
11405
by: skulkrinbait | last post by:
Hello How can I convert a date into the Unix timestamp? I don't really mind what format the date is in, something like MMDDYY would be fine, can someone show me what code I would need to do that please/ Thanks.
3
12350
by: Jonathan | last post by:
I have taken up C++ programming again and need to write a socket client, so far I am able to create the connection to the socket. As I need a unix timestamp in char to put on a socket in a HTTP 1.1 GET request I am looking for a way to convert the unix timestamp to a char? I am using the following code to generate my unix timestamp: ...
6
3932
by: Geoff Cox | last post by:
Hello, at the moment I can add the combined date and time into MySQL using php $dt1 = date("Y-m-d H:i:s"); is it possible to add the date and time separately? I thought it might be
0
7894
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8172
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7929
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6577
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3814
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3841
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2328
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1424
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1152
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.