Posts Tagged ‘datetime’

Convert DateTime From PHP to MySql Format

When using web technologies PHP and MySql on a web application, you may come across the need to add the current DateTime in your database. A simple way to get the server time in PHP is to use the $_SERVER['REQUEST_TIME'] function. It will return the time in seconds since January 1, 1970. In our example, we return the number of seconds to a variable $timestampInSeconds.

$timestampInSeconds = $_SERVER['REQUEST_TIME'];

The next step once you get the the seconds is to convert it into a format that MySql will understand. In particular, MySql DateTime is ‘2008-08-01 20:01:05′. Pay attention to the leading zeros in front of the month, day, hours, minutes, and seconds. Also note that the hour field is a twenty four hour field. To accomplish this string format in PHP, we can utilize the date function. The below example will store in $mySqlDateTimea date format MySql will understand.

$mySqlDateTime= date("Y-m-d H:i:s", $timestampInSeconds);

You now have a datetime variable stored in $mySqlDateTime that can be used in a sql statement for MySql.

Get Date Difference in C#

To get the difference between two dates in C# is easy given the built in functions. The method requires two DateTime variables. In the example below, we will calculate the difference between two string dates.

string startDateString = "1/10/2006";
string endDateString = "3/24/2007";
DateTime startDate = Convert.ToDateTime(startDateString);
DateTime endDate = Convert.ToDateTime(endDateString);
TimeSpan dateDifference = endDate.Subtract(startDate);
int days = dateDifference.Days;

In the example above, two random dates are assigned to strings (startDateString and endDateString). The ToDateTime function of the Convert class is utilized to convert both strings into type DateTime. Finally, the subtract function is called on the future date and the result passed to the TimeSpan class. With the TimeSpan class, the difference in days, hours, milliseconds, minutes, and seconds can be determined. Our example above example is days.

More specifically, the TimeSpan class is capable of returning to either full integers as days, hours, milliseconds, minutes, and seconds. The second option is to return as doubles full and partial days, hours, milliseconds, minutes, and seconds. Additionally, this process will work with the full DateTime format.