Jump to content

Time conversion


unknown1

Recommended Posts

Another PHP'er is asking this too:

 

http://www.phpfreaks.com/forums/index.php/topic,280683.msg1329657.html#msg1329657

 

You'll want to add the following method to one of your classes for converting mysql date formats to unix timestamp, or you can use the mysql function UNIX_TIMESTAMP() in your query: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_unix-timestamp

 

<?php
public static function make_tstamp($date, $default_return_value=0, $default_time='00:00:00'){
	if(!is_string($date)) return $default_return_value;

	$date_parts = explode(' ', $date);
	if(count($date_parts)==1){
		// date only
		list($year, $month, $day) = explode('-', $date_parts[0]);
		list($hour, $min, $sec) = explode(':', $default_time);
		if(intval($hour+$min+$sec+$year+$month+$day)===0){
			return 0;
		}
		return mktime(intval($hour), intval($min), intval($sec), intval($month), intval($day), intval($year));
	}elseif(count($date_parts)==2){
		// date and time
		list($year, $month, $day) = explode('-', $date_parts[0]);
		list($hour, $min, $sec) = explode(':', $date_parts[1]);
		if(intval($hour+$min+$sec+$year+$month+$day)===0){
			return 0;
		}
		return mktime(intval($hour), intval($min), intval($sec), intval($month), intval($day), intval($year));
	}else{
		// invalid date format - return default tstamp now
		return $default_return_value;
	}
}

 

Once you have the datetimes as unix timestamps and the two functions from link above, you can write something like this:

 

<?php
$row = mysql_fetch_row($resource);

$start_tstamp = your_object::make_tstamp($row['start_date']);
$end_tstamp = your_object::make_tstamp($row['end_date']);

$duration = timestamp_difference_units_to_string(timestamp_difference_to_units($start_tstamp, $end_tstamp));

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/185176-time-conversion/#findComment-977509
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.