-1

I know this question has been asked but the solutions are either outdated, not supported with Java 7 or required an external library ( which I'm hoping on avoiding because I don't want another library for this one simple use case).

But basically I have 2 dates coming from my DB and the dates are UTC. I want to get the current time of the device in UTC and check if the current time is in between the start and end date. Currently I'm getting the DB dates from the Db to the phone as UTC but the current time is coming in with the device's timezone and the comparison is wrong.

Jay Syko
  • 71
  • 2
  • 6
  • 3
    Possible duplicate of [How can I get the current date and time in UTC or GMT in Java?](http://stackoverflow.com/questions/308683/how-can-i-get-the-current-date-and-time-in-utc-or-gmt-in-java) – Shaig Khaligli Aug 16 '16 at 15:17
  • 1
    This will be a hard one to answer if you dont provide some code for context. We dont know if you are dealing with Strings, java Dates, .... Also this seems like a pure Java question, so the Android tag is probably not needed. – EJK Aug 16 '16 at 15:19

1 Answers1

1

The reason most of them are using 3rd party lib because they are more stable then what Java is providing

Getting local time in UTC:

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());

Output: Sat Jan 25 11:15:29 UTC 2014

Converting string to Date:

String startDateString = "06/27/2007";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
Date startDate;
try {
    startDate = df.parse(startDateString);
    String newDateString = df.format(startDate);
    System.out.println(newDateString);
} catch (ParseException e) {
    e.printStackTrace();
}

Finding a difference between dates:

{
        Date dt2 = new DateAndTime().getCurrentDateTime();

        long diff = dt2.getTime() - dt1.getTime();
        long diffSeconds = diff / 1000 % 60;
        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000);
        int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));

        if (diffInDays > 1) {
            System.err.println("Difference in number of days (2) : " + diffInDays);
            return false;
        } else if (diffHours > 24) {

            System.err.println(">24");
            return false;
        } else if ((diffHours == 24) && (diffMinutes >= 1)) {
            System.err.println("minutes");
            return false;
        }
        return true;
}
Smit
  • 2,078
  • 2
  • 17
  • 40
  • Thank you so much!! That last code snippit did exactly what I needed – Jay Syko Aug 16 '16 at 16:42
  • 1
    @JaySyko Welcome. Next try to be more specific, so we can help you in a better and faster way! :) Have a nice day! – Smit Aug 16 '16 at 16:55