0

Trying to convert ist into cst but I'm not getting the expected output if, I passes the hardcoded value. Expected output is>
IST:: 18-04-2022 14:11:53
CST:: 18-04-2022 03:41:53

and output I am getting after hardcode value (one month ahead)
IST:: 18-05-2022 14:10:33
CST:: 18-05-2022 03:40:33

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class datetime {

    public static void main(String[] args) throws ParseException {
        // TODO Auto-generated method stub
        Calendar Local = Calendar.getInstance();
        Local.set(2022, 4, 18, 14, 10);
        
        DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        String ist = formatter.format(Local.getTime());
        System.out.println("IST:: " + ist);
        Date theist = formatter.parse(ist);
        
        //Convertion of ist into cst
        TimeZone cst = TimeZone.getTimeZone("CST");
        formatter.setTimeZone(cst);
        String cst1 = formatter.format(theist.getTime());
        System.out.println("CST:: "+ cst1);

    }

}
  • 1
    From the documentation for `Calendar.set", the `month` parameter: "Month value is 0-based. e.g., 0 for January." There are *lots* of gotchas like this with the old `java.util.Date` and `java.util.Calendar` classes. I would strongly recommend you use the `java.time` package instead. – Jon Skeet Apr 18 '22 at 09:04
  • I recommend you don’t use `Calendar`, `SimpleDateFormat`, `Date` nor `TimeZone`. All of those classes are poorly designed, cumbersome to work with and long outdated. Instead use `ZonedDateTime`, `ZoneId` and `DateTimeFormatter`, all from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 18 '22 at 09:33
  • 1
    I also recommend against using `CST` (nor `IST`) as a time zone. It’s ambiguous. Use `America/Chicago` if this was the time zone you intended. Always use *region/city* format for time zone IDs. – Ole V.V. Apr 18 '22 at 09:34
  • The modern `ZonedDateTime` class is not so surprising. I ran `ZonedDateTime.of(2022, 4, 18, 14, 10, 0, 0, ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("America/Chicago")).format(DateTimeFormatter.ofPattern("dd-MM-uuuu HH:mm:ss"))` in Asia/Kolkata time zone and got `18-04-2022 03:40:00`. Not even any random seconds out of nowhere. – Ole V.V. Apr 18 '22 at 09:42

0 Answers0