Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateFormat Parsing error with AM/PM

I am trying to parse input string date to Date. it is unable to detect AM/PM tag in the input. It should add time to specified date and return date. But its unable to parse AM/PM tag. 03:00 PM is parsed to 03:00:00 in Date. It should be 15:00:00.

output: Date : Tue Dec 22 03:00:00 UTC 2015 Calender : Tue Dec 22 11:15:00 UTC 2015 Result : 2015-12-22 11:15 AM

Am I using wrong date format?

Here's my code:

import java.util.*;
import java.text.*;
public class Main {
   public static void main(String[] args) throws Exception {
      System.out.println("Result : "+Main.addHoursToDate("2015-12-22 03:00 `enter code here`PM",8,15,0));
   }

   public static String addHoursToDate(String date, int hoursToAdd, int minsToAdd, int secToAdd){
        String result = "";
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm aa");
            Date dt = sdf.parse(date);

            System.out.println("Date : " + dt.toString());

            Calendar cl = Calendar.getInstance();
            cl.setTime(dt);
            cl.add(Calendar.HOUR_OF_DAY, hoursToAdd);
            cl.add(Calendar.MINUTE, minsToAdd);
            cl.add(Calendar.SECOND, secToAdd);

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

            result = Main.formatDate(cl.getTime().toString(),"EEE MMM dd HH:mm:ss z yyyy","yyyy-MM-dd HH:mm aa");

            System.out.println("Calender : " + cl.getTime().toString());

        }catch(Exception e){
            return e.toString();
        }
        return result;
    }

  public static String formatDate(String date, String currentFormat, String requiredFormat) throws Exception {
        String result = "";
        boolean flag = false;
        try {
            SimpleDateFormat currentFormatter = new SimpleDateFormat(currentFormat);
            Date currentDate = currentFormatter.parse(date);

            flag = date.equals(currentFormatter.format(currentDate));
            if (!flag){
                throw new Exception();  // We are throwing this exception because the date has been parsed "successfully"  
                // but still we are not sure that it has been parsed "correctly"!!!
            }
            SimpleDateFormat requiredFormatter = new SimpleDateFormat(requiredFormat);
            result = requiredFormatter.format(currentDate);
        }catch (Exception e){
            return "";
        }

        return result;
    }

}
like image 525
Saajan Singh Avatar asked Dec 31 '15 09:12

Saajan Singh


People also ask

What is simpledateformat parse method in Java?

SimpleDateFormat parse() Method in Java with Examples. The parse() Method of SimpleDateFormat class is used to parse the text from a string to produce the Date. The method parses the text starting at the index given by a start position.

What is simpledateformat in C++?

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date → text), parsing (text → date), and normalization. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.

Why is datetime so hard to parse?

(The fact that DateTime sometimes represents a value in the system default time zone, sometimes a value in UTC, and sometimes a value with no associated time zone makes this all tricky.) Most libraries allow you to specify which culture to use when parsing (or formatting) data.

How to parse the text from a string to produce date?

The parse () Method of SimpleDateFormat class is used to parse the text from a string to produce the Date. The method parses the text starting at the index given by a start position. Parameters: The method takes two parameters: Attention reader! Don’t stop learning now.


1 Answers

Got Answer myself:

I need to use

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm aa");

instead of

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm aa");

H : is used for 24 hour notation.

refer to https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

like image 79
Saajan Singh Avatar answered Sep 21 '22 00:09

Saajan Singh