I’m receiving some date format, an ISO-something, and was wondering what the appropriate way to parse it into a timestamp.
My ultimate goal will be a standard switch on it to create “X minutes / hours / days ago.”, so if there is a tool that does that already, that’d be optimal.
I’ve tried joda-time, but it choked on it.
Here is an example of a time string:
2012-05-03 @ 15.55.05.433Z
Additionally, if it is indeed it is the case that it’s not an ISO-something format, I’ve no problem manipulating, say, the @ out of it, etc.
EDIT: Attempt 1:
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSSZ" );
try
{
Date myDate = dateFormat.parse( o.getCreationDate().replace( "@", "" ) );
long minutes = myDate.getTime() / 1000 / 60;
holder.timeText.setText( minutes + " minutes ago" );
}
catch( ParseException e )
{
e.printStackTrace();
}
Result:
05-17 16:58:05.003: W/System.err(2915): java.text.ParseException: Unparseable date: "2012-05-09 19:49:47.987Z" (at offset 24)
EDIT 2: Stripping the Z, and correct millisecond to minute conversion fixed it:
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSS" );
try
{
Date myDate = dateFormat.parse( o.getCreationDate().replace( "@ ", "" ).replace( "Z", "" ) );
Date now = new Date();
long minutes = ( now.getTime() - myDate.getTime() ) / 1000 / 60;
holder.timeText.setText( minutes + " minutes ago" );
}
catch( ParseException e )
{
e.printStackTrace();
}
First remove the
@character, then create an instance ofSimpleDateFormatthat will parse your string and return aDateobject which will enable you to get the timestamp you desire.Note you’ll need to surround with a try and catch since it can throw an exception.