androidTag
androidTag

Reputation: 5213

Android convert string to date

I'm getting date from JSON Response in string format , but right now i want to that staring date into date format. How can i convert this strActiondate﹕ = 9/28/2015 6:52:41 PM into date , so that i can insert into Sq-lite database.

I have trying this way

strActiondate = jobjVessels.getString("actionDate");                

Log.e("strActiondate ", " = " + strActiondate);
try{
    DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    Date netDate = (new Date(Long.parseLong(strActiondate)));
    Log.e("netDate "," = "+netDate);

}
catch(Exception ex){
    ex.printStackTrace();
}

I want date in same format = 9/28/2015 6:52:41 PM

Upvotes: 1

Views: 188

Answers (2)

Raghu Teja
Raghu Teja

Reputation: 225

Use this code

strActiondate = jobjVessels.getString("actionDate");

Log.e("strActiondate ", " = " + strActiondate);
try{
     DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
     Date netDate = sdf.parse(strActiondate);
     Log.e("netDate "," = "+netDate);
 }
 catch(Exception ex){
     ex.printStackTrace();
 }

Upvotes: 0

Jordi Castilla
Jordi Castilla

Reputation: 26961

This DateFormat: MM/dd/yyyy, is not valid for this date:9/28/2015 6:52:41 PM.

You need a good SimpleDateFormat that matches this string:

a   Am/pm marker        Text    PM
H   Hour in day (0-23)  Number  0
m   Minute in hour      Number  30
s   Second in minute    Number  55

So this:

String strActiondate = "9/28/2015 6:52:41 PM"; 
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
Date netDate = sdf.parse(strActiondate);
System.out.println(netDate);

Will output:

Mon Sep 28 06:52:41 CEST 2015

In your code:

try{
    DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
    Date netDate = sdf.parse(strActiondate);       
    Log.d("netDate "," = "+netDate);  // log.e is an error... so better d or i
}

Upvotes: 1

Related Questions