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.
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
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