convert dates in Unix time format
Hello all,
I have around 900 dates in the format of DD-MM-YYYY and I want to convert them in Unix time format...
Is there a way to do this? I was thinking of passing them into an array, and then, for each date, I would use the function date() I suppose and get the Unix time format of them... But I don't know the way to do it...
So, for instance, if you have:
$date_to_format='05-10-2006' , how would I get the Unix timestamp?
Thank you in advance!
andy206uk posted this at 10:27 — 11th February 2007.
He has: 1,758 posts
Joined: Jul 2002
Use mktime()
andy206uk posted this at 10:29 — 11th February 2007.
He has: 1,758 posts
Joined: Jul 2002
Oh... you would of course have to break down the original date into it's component parts. If they're all in exactly the same format it's probably easiest to do it using substr(), or you can break it into an array using explode()
Andy
andy206uk posted this at 10:54 — 11th February 2007.
He has: 1,758 posts
Joined: Jul 2002
Here's an example for you:
<?php
//**** put all dates in an array ****//
$dates = array(\"16-11-1981\",
\"19-11-1985\",
\"13-12-1984\"
);
//**** loop through dates array ****//
foreach($dates as $date) {
//**** assign parts of date to variables ****//
$dd = substr($date,0,2);
$mm = substr($date,3,2);
$yyyy = substr($date,6,4);
//**** convert to timestamp and add to timestamps array ****//
$timestamps[] = mktime(0,0,0,$mm,$dd,$yyyy);
}
//**** output timestamps ****//
print_r($timestamps);
?>
Andy
Abhishek Reddy posted this at 10:55 — 11th February 2007.
He has: 3,348 posts
Joined: Jul 2001
Or just use strtotime().
Abhishek Reddy posted this at 11:15 — 11th February 2007.
He has: 3,348 posts
Joined: Jul 2001
A slightly more general solution is to use strptime(), that allows you to declare the date format with which to parse the input string:
<?php
$d = strptime(\"05-10-2006\", \"%d-%m-%Y\");
/*
$d =>
Array
(
[tm_sec] => 139653648
[tm_min] => 0
[tm_hour] => -1074302728
[tm_mday] => 5
[tm_mon] => 9
[tm_year] => 106
[tm_wday] => 4
[tm_yday] => 277
[unparsed] =>
)
*/
$timestamp = mktime(0,0,0,
$d[tm_mon]+1, /* strptime numbers months 0-11 but mktime wants 1-12 */
$d[tm_mday],
$d[tm_year]);
?>
andy206uk posted this at 11:54 — 11th February 2007.
He has: 1,758 posts
Joined: Jul 2002
lol... that's what I love about PHP... there's always a function to do what you need. It's also what I hate - there are so many functions that it's really hard to remember them all!
Andy
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.