Search code examples
javaandroiddatetimetimezoneutc

Get Device time in UTC format regardless time zone


How i can get the local time of the device and convert it to global UTC format for my country ?


Solution

  • Not sure what you want to do, but if you want the date and time in normal format you can do it this way:

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    Calendar cal = Calendar.getInstance();
    String dateAndTime = dateFormat.format(cal.getTime());
    

    String dateAndTime will be something like 2012/01/01 11:13, according to the date & time the device was set to, so it shows the same time as the device's clock. You can play around with the format a little bit by changing "yyyy/MM/dd HH:mm" to whatever you like.

    Hope this helps!

    UPDATE: To get the UTC time do it this way:

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    String dateAndTimeUTC = dateFormat.format(new Date());