简体   繁体   中英

PHP manipulate time without dates

I'm working on a calendar application in which time of day matters, but date and year do not. An employee can enter the hours they are available (8:00AM - 9:30AM, for example) and I check that against other values.

I was using strtotime() to put the times into the database, not realizing the function would insert a date and year if none was provided. When I started to compare the employee's availability with a certain timeslot, I got no matches because all the employees timestamps said they were busy YESTERDAY. :P

Is there a good way to store just times in a database that makes it easy to compare them both in SQL and PHP? Thanks.

You are looking for the mySQL time datatype. http://dev.mysql.com/doc/refman/5.6/en/time.html

Microsoft SQL Server(2008/2012) gives you a time datatype as well. http://msdn.microsoft.com/en-us/library/bb677243.aspx

Both give you the ability to store time in 'HH:MM:SS' format. They are comparable. (For MS SQL you have a range of 00:00:00.0000000 through 23:59:59.9999999)

if you can't use the built in datatypes you can write a couple function to convert from hh:mm to int and back again.

function HourMinuteSecToDecimal($hour_minute_sec) {
        $t = explode(':', $hour_minute_sec);
        return $t[0] * 60 + $t[1] * 60 + $t[2];
}

echo HourMinuteSecToDecimal("23:30:25");
return 3205

function DecimaltoHourMinuteSec($sec, $padHours = false) {
    $hms = "";
    $hours = intval(intval($sec) / 3600);
    $hms .= ($padHours) ? str_pad($hours, 2, "0", STR_PAD_LEFT) . ':' : $hours . ':';
    $minutes = intval(($sec / 60) % 60);
    $hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT) . ':';
    $seconds = intval($sec % 60);
    $hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);
    echo $hms;
}

echo DecimaltoHourMinuteSec(3205);
return 23:30:25

Well, I see two ways here:

1: Save your timestamps as timestamp and then modify your query so that you select just the time from your timestamp.

2: use a string field and save your times in the format hhmm (eg 0112 being 1am 12 min or 1547 being 3pm 47 minutes) and then use your select on that. I know, doesn't seem very nice, but then again: If you where using a mysql database and using time as a datatype - it would be a formatted string, too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM