Date and time conversion to some other Timezone in java

后端 未结 10 484
失恋的感觉
失恋的感觉 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条回答
  •  盖世英雄少女心
    2020-12-11 22:07

    Your mistake is to call parse instead of format.

    You call parse to parse a Date from a String, but in your case you've got a Date and need to format it using the correct Timezone.

    Replace your code with

    Calendar currentdate = Calendar.getInstance();
    DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    TimeZone obj = TimeZone.getTimeZone("CST");
    formatter.setTimeZone(obj);
    System.out.println("Local:: " +currentdate.getTime());
    System.out.println("CST:: "+ formatter.format(currentdate.getTime()));
    

    and I hope you'll get the output you are expecting.

提交回复
热议问题