bloppit bloppit - 2 months ago 20
Javascript Question

How can I convert Twitter API post time/date to valid ISO format?

Yo guys, I'm building a twitter interface and want to display the times like Twitter itself.

I perform a get request and grab the tweet, I then pass it into

moment.js
in order to convert it.

Here is a code snippet of this:

client.get('direct_messages', {screen_name: 'theclearytheory', count: '3'}, function(error, messages, response){
if(!error){
var privateMessageTime = [];

for(var i=0; i < messages.length; i++){
console.log(messages[i].created_at);
privateMessageTime.push(moment(messages[i].created_at).fromNow());
}
} else {
console.log(error)
}


Right now, this DOES work fine. If I get back
Sun Oct 02 11:59:43 +0000 2016
then the program correctly turns this into:
2 months ago
.

The problem is that I'm getting this warning message in the console:

Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments:
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: Fri Jul 22 10:19:18 +0000 2016, _f: undefined, _strict: undefined, _locale: [object Object]


I have scoured over the documentation it links to but I just can't work out how to work with this. If anyone has any experience with this (or is that much smarter than me), I'd really appreciate any help please!

Answer

I would refer to the section in the docs on strict mode. http://momentjs.com/guides/#/parsing/strict-mode/ you can use your code and then add your desired format as a string for the second argument and true as the third argument and chain .format() see below:

client.get('direct_messages', {screen_name: 'theclearytheory', count: '3'}, function(error, messages, response){
            if(!error){
                var privateMessageTime = [];

                for(var i=0; i < messages.length; i++){
                    console.log(messages[i].created_at);
                    privateMessageTime.push(moment(messages[i].created_at, 'MM/DD/YYYY', true).format().fromNow());
                }
            } else {
                console.log(error)
            }