Lavish Khetan
Lavish Khetan

Reputation: 59

How to convert UTC to SGT

Below are two methods which I am using to convert UTC to SGT with not much of a success. Please help me to convert UTC to SGT.

List<String> list0 = new ArrayList<>();
List<String> list1 = new ArrayList<>();

public void FirstTradingTime() throws ParseException {
     list0 .add("2018-05-10T05:56:35.557Z");
       for(int i=0; i<list0 .size();i++) {
       String FirstTime = list0 .get(i);
       DateFormat pstFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
       pstFormat.setTimeZone(TimeZone.getTimeZone("PST"));
       Date date = pstFormat.parse(String.valueOf(FirstTime));          
       DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
       utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
       list1 .add(utcFormat.format(date));
  }
  System.out.println("FirstTradingTime "+list1 ;
}

This above method fetches me output: [2018-05-10 12:56:35.557]

My expected output is: 2018-05-10 13:56:35.557

List<String> list2 = new ArrayList<>();
List<String> list3 = new ArrayList<>();

public void FirstTradingTime() throws ParseException {
   list2 .add("2018-05-10T05:56:35.557Z");
   for (int i = 0; i < list2 .size(); i++) {
       String Str = list2 .get(i);
       Instant timestamp = Instant.parse(Str);
       ZonedDateTime SGTtime = timestamp.atZone(ZoneId.of("Singapore"));

       list3 .add(String.valueOf(SGTtime));
       System.out.println(list3);
   }
}

This above method fetched me output: [2018-05-10T13:56:35.557+08:00[Singapore]]

Expected output: 2018-05-10 13:56:35.557

Upvotes: 2

Views: 5147

Answers (1)

aranchal
aranchal

Reputation: 36

The mistake is in TimeZone.getTimeZone("SGT") because the id SGT doesn't exist. The id for that time zone is Asia/Singapore and you can get it with TimeZone.getTimeZone("Asia/Singapore").

Try with this:

DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utcDate = utcFormat.parse("2018-05-10T05:56:35.557");

DateFormat sgtFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
sgtFormat.setTimeZone(TimeZone.getTimeZone("Asia/Singapore"));
String sgtString = sgtFormat.format(utcDate);

Upvotes: 1

Related Questions