0

I have calendar object created in system timezone which is of "EDT". When ever i get the cal.getTime(); it prints the date of EDT. How can i get the date of the same calendar in UTC?

I am just trying to convert it to string using the below snippet

   `Calendar cal = Calendar.getInstance();      
    String definedDate = CalendarUtils.toString(cal, "MM/dd/yyyy");
    System.out.println(definedDate); 


public static String toString(Calendar cal, String pattern) {
    String str = "";
    if (cal!= null) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        str = dateFormat.format(cal.getTime());
        LOGGER.error("Date : "+str);
    }
    return str;
}

`

Arun
  • 609
  • 2
  • 12
  • 33

3 Answers3

1

Try Below code, set time zone to DateFormat as DateFormat.setTimeZone():

TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat = 
       new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);

System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();

System.out.println("UTC:     " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());
Prabhat Kumar
  • 256
  • 2
  • 9
  • Yes it works. Thanks for your input. how can we get the same calendar in UTC instance. here we are converting it to string. – Arun Aug 09 '16 at 08:14
  • Please mark it as solved, if it works for you. simpleDateFormat.parse("Date in String Format") should work for you. – Prabhat Kumar Aug 09 '16 at 09:20
0

Get calendar instance using below snippet...

Calendar cal= Calendar.getInstance(TimeZone.getTimeZone("UTC"));

Or change timezone to utc as following...

cal.setTimeZone(TimeZone.getTimeZone("UTC"));
User
  • 4,023
  • 4
  • 37
  • 63
0
Calendar c2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c2.set(year, month, date, hourOfDay, minute, second);
System.out.println(sdf.format(c2.getTime()));
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Mosen
  • 1
  • Although this code may help to solve the problem, providing additional context regarding _why_ and/or _how_ it answers the question would significantly improve its long-term value. Please [edit] your answer to add explanation, including what limitations and assumptions apply. – Toby Speight Aug 09 '16 at 09:11