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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • perplexed

    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.

  • perplexed

    #2
    Re: Convert User entered date and time to Unix Timestamp before inserting to database

    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);
    ?>

    Comment

    • Tim Van Wassenhove

      #3
      Re: Convert User entered date and time to Unix Timestamp before inserting to database

      In article <1102902388.009 674.102040@c13g 2000cwb.googleg roups.com>, perplexed wrote:[color=blue]
      > 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?[/color]

      here are some never-to-forget functions:

      mysql: dateformat, from_unixtime, unixtime
      php: strtotime



      --
      Met vriendelijke groeten,
      Tim Van Wassenhove <http://www.timvw.info>

      Comment

      • scotty

        #4
        Re: Convert User entered date and time to Unix Timestamp before inserting to database

        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

        Comment

        • perplexed

          #5
          Re: Convert User entered date and time to Unix Timestamp before inserting to database

          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

          Comment

          • Jan Pieter Kunst

            #6
            Re: Convert User entered date and time to Unix Timestamp before insertingto database

            perplexed wrote:[color=blue]
            > 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.[/color]


            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, <devnull@cauce. org> is een "spam trap".
            E-mail adres is <jpk"at"akamail .com>, waarbij "at" = @.

            Comment

            • Geoff Berrow

              #7
              Re: Convert User entered date and time to Unix Timestamp before inserting to database

              I noticed that Message-ID:
              <1102910914.898 598.227430@z14g 2000cwz.googleg roups.com> from perplexed
              contained the following:
              [color=blue]
              >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.[/color]

              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/

              Comment

              • Michael Fesser

                #8
                Re: Convert User entered date and time to Unix Timestamp before inserting to database

                .oO(scotty)
                [color=blue]
                >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![/color]

                sprintf() might come in handy to add leading zeros where necessary:

                $temp_date = sprintf('%u-%02u-%02u %02u:%02u:00', ...);
                [color=blue]
                >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));[/color]

                Much too complicated, DATE_FORMAT() and UNIX_TIMESTAMP( ) exist in MySQL.
                [color=blue]
                >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?[/color]

                Yep.

                Micha

                Comment

                • Michael Fesser

                  #9
                  Re: Convert User entered date and time to Unix Timestamp before inserting to database

                  .oO(perplexed)
                  [color=blue]
                  >How do you convert a user inputted date to a unix timestamp before
                  >insterting it into your database?[/color]

                  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

                  Comment

                  • Michael Fesser

                    #10
                    Re: Convert User entered date and time to Unix Timestamp before inserting to database

                    .oO(perplexed)
                    [color=blue]
                    >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.[/color]

                    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

                    Comment

                    • scotty

                      #11
                      Re: Convert User entered date and time to Unix Timestamp before inserting to database

                      >Much too complicated, DATE_FORMAT() and UNIX_TIMESTAMP( ) exist in
                      MySQL.

                      I'm somewhat new to MYSQL, so I agree should use existing functions to
                      perform the translations where possible, depending upon your form input.

                      Comment

                      • Michael Fesser

                        #12
                        Re: Convert User entered date and time to Unix Timestamp before inserting to database

                        .oO(scotty)
                        [color=blue][color=green]
                        >>Much too complicated, DATE_FORMAT() and UNIX_TIMESTAMP( ) exist in[/color]
                        >MySQL.
                        >
                        >I'm somewhat new to MYSQL[/color]

                        OK. ;)
                        [color=blue]
                        >so I agree should use existing functions to
                        >perform the translations where possible, depending upon your form input.[/color]

                        Yep. You can do much more things in a query than just the usual SELECTs,
                        even complex calculations and manipulations. If the database is able to
                        do such things and return any data in any particular format you like,
                        why not use it? Keeps the PHP code smaller.

                        Micha

                        Comment

                        • scotty

                          #13
                          Re: Convert User entered date and time to Unix Timestamp before inserting to database

                          Thanks for the tip. There is a lot I'm not aware of. New to MYSQL.
                          In the recent past I created something that involved dates. I just now
                          changed the data definition you mentioned and it still works fine. The
                          field is now a DATETIME field but is being created with the same
                          TIMESTAMP. So it looks like this functions the same but is now
                          historical rather than the auto-update that you mention?

                          I look forward to going through my edit routines and inserting some of
                          the functions mentioned in these comments, where applicable, to make it
                          more concise where possible. Although I did not ask the original
                          question here, I appreciate the comments and hope that some of my
                          original comments helped as well.

                          Comment

                          • Michael Fesser

                            #14
                            Re: Convert User entered date and time to Unix Timestamp before inserting to database

                            .oO(scotty)
                            [color=blue]
                            >Thanks for the tip. There is a lot I'm not aware of. New to MYSQL.
                            >In the recent past I created something that involved dates. I just now
                            >changed the data definition you mentioned and it still works fine. The
                            >field is now a DATETIME field but is being created with the same
                            >TIMESTAMP. So it looks like this functions the same but is now
                            >historical rather than the auto-update that you mention?[/color]

                            There are still important differences. It's all explained in the manual.

                            The DATETIME, DATE, and TIMESTAMP Types


                            TIMESTAMP Properties Prior to MySQL 4.1


                            TIMESTAMP Properties as of MySQL 4.1


                            Micha

                            Comment

                            Working...