Convert a date and time string according to UTC format
Best way to get formatted string of Date in required format is
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String formatted = dateFormat.format(date);
Get UTC from current time :
public String getCurrentUTC(){
Date time = Calendar.getInstance().getTime();
SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
return outputFmt.format(time);
}
Your df
and inputFmt
must use the same format.
But I think you should do it like this:
Date myDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(myDate);
Date time = calendar.getTime();
SimpleDateFormat outputFmt = new SimpleDateFormat("MMM dd, yyy h:mm a zz");
String dateAsString = outputFmt.format(time);
System.out.println(dateAsString);