How to get a date (Moscow time) and compare it to a line of yyyyy-MM-dd.



  • There's a line:

    String dateFromServer = "2015-12-16";
    

    How to get the object right. Date (in Moscow) and compare it to that line (in advance/after)?



  • The most convenient way to deal with the dates in Java (at least until Java 😎 is to use the JodaTime Library.

    It's all about transforming the line into a local date. http://joda-time.sourceforge.net/apidocs/org/joda/time/LocalDate.html (i.e. a date without clockwork) and a local date on Moscow. And then compare them:

    String dateFromServer = "2015-12-16";
    LocalDate serverDate = LocalDate.parse(dateFromServer);
    LocalDate localDate = new LocalDate(DateTimeZone.forID("Europe/Moscow"));
    

    System.out.println(localDate.compareTo(serverDate));


    For Java 8+, the code will be very similar to JodaTime:

    String dateFromServer = "2015-12-16";
    LocalDate serverDate = LocalDate.parse(dateFromServer);
    LocalDate localDate = LocalDate.now(ZoneId.of("Europe/Moscow"));

    System.out.println(localDate.compareTo(serverDate));


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2