0

Hi for some of the requirement i need to convert the string representation of date(with no format) to date object and convert back to string(with a specific format)

This is what i tried so far, the output is not coming as expected and it's printing something like 08140009 - Any idea what is this

And please provide any suggestions.

MY code is :

public String getDateBackToCST(String  createDate){

    SimpleDateFormat dateFormatter = new SimpleDateFormat("MMddyyyy");
    TimeZone obj = TimeZone.getTimeZone("CST");
    dateFormatter.setTimeZone(obj);
    Date createdDate = null;

    try {
        createdDate = dateFormatter.parse(createDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dateFormatter.format(createdDate);
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

1 Answers1

0

You need to specific proper flags for SimpleDateFormat. You have 2 options to specify timezone z and Z and to specify day name use E like this

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Main {



    public static void main(String[] args) throws ParseException {

        String date = "Sat Sep 20 23:39:04 IST 2014 ";
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
        System.out.println(sdf.parse(date));

    }
}
sol4me
  • 15,233
  • 5
  • 34
  • 34
  • Yes it is correct, but whenever we call parse method we will loose the timezone information which Date object will not contain. I want the returned string to be in CST timezone – manjunatha citragar Sep 20 '14 at 18:18
  • @manjunathacitragar Date object is never associated with any timezone – SparkOn Sep 20 '14 at 18:19
  • Yes i agree.. The String createDate which is passed to the function is in CST timezone and when i parse it and format it back i want it to be in CST timezone only. – manjunatha citragar Sep 20 '14 at 18:23