Sunday, 26 December 2010

Java - How to Convert String to Date and Date to String for Android App

To convert a date in string format to a date in java date format the java SimpleDateFormat method is used. You define your own custom date structure using the java simple date format.

In my code below I use the format “EEE MMM dd HH:mm:ss”. This means the date will, for example, look something like this: “Mon Jan 04 07:40:22 2011”.

The string you have needs to exactly match this format. For a list of the different ways of setting a simple date string see http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

What I was trying to do with my android app was to convert the published date string that the Google Search API gave me (within a JSON object) as a query result. The initial date string that Google gave me was not the way I wanted to structure my date so I used the java substring method to manually alter the string content to the required format before I performed the date conversion below:

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy");

Date mydate = sdf.parse(datestring);


To do the opposite, to convert the date back to a string, you can use the following code:

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy");

String datestring = sdf.format(date);


Thanks for reading, please check back at the Android Adam blog for more Java and Android solutions.

1 comment:

  1. Adam, I recommend trying https://poeditor.com/ when you need to translate your Android app in multiple languages. It has many useful features such as API, translation memory, WordPress plugin, GitHub and BitBucket integration, as well as a flexible and simple interface to make things easier for everyone.

    ReplyDelete