Converting date without time for different timezone

狂风中的少年 提交于 2019-12-02 08:54:31

问题


I store the date in UTC long and displayed in user timezone. But when I try to store only days without time it misleading to different dates.

Eg: Scheduling event on 05/06/2016 (06 May 2016). This date is unique for all regions without timezone. If user from GMT+5:30 timezone trying to add a event on 05/06/2016 then it ISO-8601 format is 2016-05-05T16:00:00.000Z and milliseconds is 1462464000000.

Then user from GMT timezone try to view this event. The date will be 05/05/2016 instead of 05/06/2016.

Is there any way to convert date without any timezone.


回答1:


Java 8 provides the solution for your problem. If you can use Java 8, use java.time.LocalDate which represents only the date without the time. Store the long value returned by toEpochDay method. A sample code is given below:

LocalDate date = LocalDate.of(2016, 5, 4);
// Store this long value
long noOfDays = date.toEpochDay(); // No of days from 1970-01-01
LocalDate newDate = LocalDate.ofEpochDay(noOfDays);
System.out.println(newDate); // 2016-05-04



回答2:


Always store the whole timestap. Whenever you want to display just convert the timestamp to whichever timezone you want to convert it to & display it.

These would help in conversions: (Time-stamp to Date or viseversa)

// timestamp to Date
long timestamp = 5607059900000; //Example -> in ms
Date d = new Date(timestamp );

// Date to timestamp
long timestamp = d.getTime();

//If you want the current timestamp :
Calendar c = Calendar.getInstance();
long timestamp = c.getTimeInMillis();

Refer : convert TimeStamp to Date in Java

You may display different date formats using SimpleDateFormat.

Eg:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainClass {
  public static void main(String[] args) {
    String pattern = "MM/dd/yyyy";
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    try {
      Date date = format.parse("12/31/2006");
      System.out.println(date);
    } catch (ParseException e) {
      e.printStackTrace();
    }
    // formatting
    System.out.println(format.format(new Date()));
  }
}


来源:https://stackoverflow.com/questions/37018257/converting-date-without-time-for-different-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!