Convert Date/Time for given Timezone - java

前端 未结 16 2291
孤城傲影
孤城傲影 2020-11-22 12:36

I want to convert this GMT time stamp to GMT+13:

2011-10-06 03:35:05

I have tried about 100 different combinations of DateFormat, TimeZone,

16条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 13:04

    For me, the simplest way to do that is:

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    
    //Here you say to java the initial timezone. This is the secret
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    //Will print in UTC
    System.out.println(sdf.format(calendar.getTime()));    
    
    //Here you set to your timezone
    sdf.setTimeZone(TimeZone.getDefault());
    //Will print on your default Timezone
    System.out.println(sdf.format(calendar.getTime()));
    

提交回复
热议问题