0

I am trying to convert UTC time to local time.

UTC Time : 1465389050

I tried below code.But it is not printing or showing the result.So I am not sure this code will work or not.

MainActivity.java:

String created = "1465389050";

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        try {
            Date myDate = simpleDateFormat.parse(created);

            Log.e("myDate", ""+myDate);

            Toast.makeText(getApplicationContext(), myDate.toString(), Toast.LENGTH_LONG).show();

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
Steve
  • 1,153
  • 2
  • 15
  • 29
  • Possible duplicate of [Java Convert GMT/UTC to Local time doesn't work as expected](http://stackoverflow.com/questions/19375357/java-convert-gmt-utc-to-local-time-doesnt-work-as-expected) – Rod_Algonquin Jun 08 '16 at 13:54
  • `new Date(YourTimestampAsInteger * 1000)` should already create a Date object in local time ... – devnull69 Jun 08 '16 at 14:03

2 Answers2

0

Try this

 long timestamp = 1465389050L;
    Date date = new Date(timestamp);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
    calendar.setTime(date);

now you have the to convert the UTC time to your local time

eddykordo
  • 607
  • 5
  • 14
0

As I said in a comment already: new Date(YourTimestampAsLong * 1000) will already give you local time. No need to set TimeZone.

Date date = new Date((long)1465389050 * 1000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);

Output:

2016-06-08 14:30:50
devnull69
  • 16,402
  • 8
  • 50
  • 61