0

How can I convert a time string like this:

30/7/2010

to a UNIX timestamp?

I tried strtotime() but I get a empty string :(

1
  • 1
    strtotime doesn't work because (from the doc) "The function expects to be given a string containing a US English date format" Commented Jul 27, 2010 at 22:05

5 Answers 5

10

PHP >= 5.3:

$var = DateTime::createFromFormat('j/n/Y','30/7/2010')->getTimestamp();
Sign up to request clarification or add additional context in comments.

Comments

5

You're using UK date format.

Quick and dirty method:

$dateValues = explode('/','30/7/2010');
$date = mktime(0,0,0,$dateValues[1],$dateValues[0],$dateValues[2]);

1 Comment

This is what I came up with too -- is there really no function that takes a date format string and a textual date string and returns the timestamp? It seems like a weird gap in PHP's date interface
2

You probably want to use https://www.php.net/manual/en/function.strptime.php (strptime) since your date is in a different format than what PHP might be expecting.

1 Comment

+1. If you've got PHP >= 5.1 and a date format that doesn't work with strtotime, strptime is definitely an option.
0

You could also convert it to a format that strtotime() can accept, like Y/M/D:

$tmp = explode($date_str);
$converted = implode("/", $tmp[2], $tmp[1], $tmp[0]);
$timestamp = strtotime($converted);

1 Comment

If you're going to do that you might as well just mktime(0, 0, 0, $tmp[1], $tmp[0], $tmp[2]);
0

The PHP 5.3 answer was great

DateTime::createFromFormat('j/n/Y','30/7/2010')->getTimestamp();

Here is a < 5.3.0 solution

$timestamp = getUKTimestamp('30/7/2010');

function getUKTimestamp($sDate) {
    list($day, $month, $year) = explode('/', $sDate);
    return strtotime("$month/$day/$year");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.