0

I have used Calendar class for setting date and SimpleDateFormat for formatting. Output not as expected.

Input given = 30-9-2018 14:24  
Expected output = 30 Sep 2018 Sun 2 : 24 PM  
Returned output = 01 Oct 2018 Mon 02 : 24 AM

Called as dateTimeFormat(30,9,2018,14,24,"dd MMM yyyy EEE hh : mm a");

Below is my code

    public static String dateTimeFormat(int date,int month,int year,int curr_hour,int curr_min,String format){


      Log.e("Given Date",date+"-"+month+"-"+year+" "+curr_hour+":"+curr_min);


     Calendar cal = Calendar.getInstance();

     cal.set(Calendar.YEAR,year);

     cal.set(Calendar.MONTH,month-1);

     cal.set(Calendar.DATE,date);

     cal.set(Calendar.HOUR,curr_hour);

     cal.set(Calendar.MINUTE,curr_min);

     SimpleDateFormat format1 = new SimpleDateFormat(format);
     String dateF = format1.format(cal.getTime());

     return dateF;

}

Android monitor screenshot in android studio

Krishna
  • 65
  • 1
  • 9
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Sep 30 '18 at 11:40
  • 1
    Hard to say without knowing how you’ve created your `SimpleDateFormat`, Could you [create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve), please? – Ole V.V. Sep 30 '18 at 11:42
  • Can you try to set AM and PM also – Syed Qasim Ahmed Sep 30 '18 at 11:43
  • Modern solution: `LocalDateTime.of(2018, 9, 30, 14, 24).format(DateTimeFormatter.ofPattern("dd MMM uuuu EEE h : mm a", Locale.ENGLISH))`. Gives `30 Sep 2018 Sun 2 : 24 PM`. If your Android API level is under 26, add [the ThreeTenABP library](https://github.com/JakeWharton/ThreeTenABP) to your project in order to use java.time, the modern Java date and time API, and it will work there too. – Ole V.V. Sep 30 '18 at 11:48
  • Thanks for your reply Ole V. I will try and say you about ThreeTenABP, but why can't the above code does not return the expected result. – Krishna Sep 30 '18 at 11:53
  • 1
    [This works](https://stackoverflow.com/questions/50317791/getactualminimum-with-hour-as-argument-of-calendar-returns-12-in-java) – Krishna Sep 30 '18 at 12:06

0 Answers0