19

I am having a date string 2012-11-21 13:11:25 which I get from local database. I have to convert this according to UTC settings and display it on a particular screen. So if its GMT+05:30 it should be displayed as 2012-11-21 18:41:25 on the screen. How can I do this conversion. I have checked some of the questions but that didn't work out.

I am able to get a Date object that returns something like Wed Nov 21 13:11:25 GMT+05:30 2012 after this I need to get the time as 18:41:25 and date as 11-21-2012

Thanks in advance

Lavanya
  • 3,903
  • 6
  • 31
  • 57
  • You can check this out: [Convertion][1] [1]: http://stackoverflow.com/questions/2609360/converting-local-timestamp-to-utc-timestamp-in-java Hope this helps. – kittu88 Nov 20 '12 at 12:31

4 Answers4

23

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);
}
SANAT
  • 8,489
  • 55
  • 66
22

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);
Kai
  • 38,985
  • 14
  • 88
  • 103
4

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);
Gurgen Hakobyan
  • 951
  • 10
  • 13
0
    //This is my input date 

    String dtStart = "2019-04-24 01:22 PM";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
    Date date = null;
    try {
        date = format.parse(dtStart);
        getDateInUTC(date)

    } catch (ParseException e) {
        e.printStackTrace();
    }

//This Method use for convert Date into some UTC format

public static String getDateInUTC(Date date) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
            String dateAsString = sdf.format(date);
            System.out.println("UTC" + dateAsString);
            return dateAsString;

        }