sree
sree

Reputation: 121

simpledateformat parse not parsing date properly

i am trying to print the date as : 2013/11/20 08 30 but it is printing as below after parsing the date through simpledateformat Wed Nov 20 14:00:00 IST 2013, here i passed the HH and MM as 08 30 but after parsing it changed to 14:00:00

Can you please suggest

public class PrintDate {

public static void main(String[] args) {
    System.out.println(getDate("2013/11/20","08","30"));


}

public static Date getDate(String date, String hour, String miniute) {

    final SimpleDateFormat displayDateTimeFormat = new SimpleDateFormat("yyyy/MM/dd HH mm");

    displayDateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    String paddedHour = hour.length() == 2 ? hour : "0" + hour;    
    int min = Integer.valueOf(miniute);
    int remainder = min % 5;
    int roundMinute = remainder > 2 ? min - remainder + 5 : min - remainder;
    String minuteStr = String.valueOf(roundMinute);
    String paddedMinuteStr = minuteStr.length() == 2 ? minuteStr : "0" + minuteStr;

    String startDateStr = date + " " + paddedHour.toUpperCase() + " " + paddedMinuteStr;

    Date startDate = null;
    try {           
        startDate = displayDateTimeFormat.parse(startDateStr);
    } catch (ParseException e) {

    }
    return startDate;

}

}

Upvotes: 0

Views: 1918

Answers (2)

Neelam Sharma
Neelam Sharma

Reputation: 2855

Just try below lines of code to get date in desired format -

Date date=new Date(2013-1900,10,20,8,30);              
SimpleDateFormat dateFormat = new SimpleDateFormat("yyy/MM/dd K mm");
String strFormatDate = dateFormat.format(date);               
Date dtFormatDate = dateFormat.parse(strFormatDate);
System.out.println("Formatted date in String:"+strFormatDate);
System.out.println("Formatted Date:"+dtFormatDate);

Just give K instead of HH in date format. You can give date as 14 30 then also this format will convert date as you desired.

Thanks

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499800

after parsing the date through simpledateformat Wed Nov 20 14:00:00 IST 2013, here i passed the HH and MM as 08 30 but after parsing it changed to 14:00:00

Yes, because you specified that you wanted it to be parsed as a UTC value. However, the Date itself has no concept of a time zone - it's just an instant in time. Date.toString() will always use the default time zone.

2013-11-20 08:30 UTC is the same instant in time as 2013-11-20 14:00 IST, so it's actually parsing it correctly - it's just the result of Date.toString() which is confusing you.

If you want to preserve the time zone as well, you'll have to do that separately - or (better) use Joda Time which is a much nicer date/time API, and has a DateTime class which represents an instant in time in a particular calendar system and time zone.

Upvotes: 2

Related Questions