1

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.

Dineshkani
  • 2,899
  • 7
  • 31
  • 43
  • Why don't you take time into account when computing and display only date part? E.g. you create your event date as 2016-06-05T05:30:00.000Z, convert it to target timezone (if required) and display only date part? – Aakash May 04 '16 at 04:10
  • "*I store the date in UTC*" => where do you store it? In a variable? In a database? If in a database, what is the column type? etc. – assylias May 04 '16 at 07:21

2 Answers2

3

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
Gobinath
  • 904
  • 1
  • 15
  • 23
  • If using Java 6 or 7 you can still use this solution. `java.time`, the modern Java date and time API, has been backported. Add [ThreeTen Backport](http://www.threeten.org/threetenbp/) to your project and you’re going. – Ole V.V. May 08 '18 at 11:24
1

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()));
  }
}
Community
  • 1
  • 1
Ani Menon
  • 27,209
  • 16
  • 105
  • 126