开发者

Parsing Twitter API Datestamp

开发者 https://www.devze.com 2022-12-26 21:35 出处:网络
I\'m using the twitter API to return a list of status updates and the times they were created. It\'s returning the creation date in the following format:

I'm using the twitter API to return a list of status updates and the times they were created. It's returning the creation date in the following format:

Fri A开发者_运维技巧pr 09 12:53:54 +0000 2010

What's the simplest way (with PHP or Javascript) to format this like 09-04-2010?


Cross-browser, time-zone-aware parsing via JavaScript:

var s = "Fri Apr 09 12:53:54 +0000 2010";

var date = new Date(
    s.replace(/^\w+ (\w+) (\d+) ([\d:]+) \+0000 (\d+)$/,
        "$1 $2 $4 $3 UTC"));

Tested on IE, Firefox, Safari, Chrome and Opera.


strtotime("dateString"); gets it into the native PHP date format, then you can work with the date() function to get it printed out how you'd like it.


JavaScript can parse that date if you remove the +0000 from the string:

var dStr = "Fri Apr 09 12:53:54 +0000 2010";
dStr = dStr.replace("+0000 ", "") + " UTC";
var d = new Date(dStr);

Chrome -- and I suspect some other non IE browsers -- can actually parse it with the +0000 present in the string, but you may as well remove it for interoperability.

PHP can parse the date with strtotime:

strtotime("Fri Apr 09 12:53:54 +0000 2010");


Here is date format for Twitter API:

Sat Jan 19 20:38:06 +0000 2013
"EEE MMM dd HH:mm:ss Z yyyy" 


Javascript. As @Andy pointed out, is going to be a bitch when it comes to IE. So it's best to rely on a library that does it consistently. DateJS seems like a nice library.

Once the library is added, you would parse and format it as:

var date = Date.parse("Fri Apr 09 12:53:54 +0000 2010");
var formatted = date.toString("dd-MM-yyyy");

In PHP you can use the date functions or the DateTime class to do the same (available since PHP 5.2.0):

$date = new DateTime("Fri Apr 09 12:53:54 +0000 2010");
echo $date->format("d-m-Y"); // 09-04-2010


FYI, in Java it is:

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);
Date d = sdf.parse(dateAsString);

sdf = new SimpleDateFormat("dd-MM-yyyy");
String s = sdf.format(d);


And in Swift:

let dateString = "Fri Apr 09 12:53:54 +0000 2010"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
let date = dateFormatter.date(from: dateString)

0

精彩评论

暂无评论...
验证码 换一张
取 消