Date and time conversion to some other Timezone in java

后端 未结 10 486
失恋的感觉
失恋的感觉 2020-12-11 21:13

i have written this code to convert the current system date and time to some other timezone. I am not getting any error but i am not getting my output as expected. Like if i

10条回答
  •  旧时难觅i
    2020-12-11 21:45

    Problem is when you print date obj it call toString method and it will print in your machines default time zone. Try this code and see difference.

    Calendar currentdate = Calendar.getInstance();
    String strdate = null;
    DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ssz");
    strdate = formatter.format(currentdate.getTime());
    System.out.println("strdate=>" + strdate);
    TimeZone obj = TimeZone.getTimeZone("CST");
    
    formatter.setTimeZone(obj);
    strdate = formatter.format(currentdate.getTime());
    Date theResult = formatter.parse(strdate);
    
    System.out.println("The current time in India is  :: " +currentdate.getTime());
    
    System.out.println("The date and time in :: " + obj.getDisplayName() + "is ::" + theResult);
    System.out.println("The date and time in :: " + obj.getDisplayName() + "is ::" + strdate);
    

提交回复
热议问题