Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Date object is always one day less

I have user date picker where a user selects the date and it then makes an AJAX call to a rest service implemented in Java. But the issue is it always returns one-day previous date object. Here is my implementation:

testDate = $("#date-select").val();
console.log(testDate)

Above console.log prints the correct date. 2018-04-22 But when it gets passed to rest service, it shows the wrong date:

@POST
@Path("checkDate/{testDate}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response demoService(final DemoBean demoBean)
{
    System.out.println("Rest service got called:"+ demoBean.getDate());
    if(demoDateConfService.setDate(demoBean.getDate())
    {
        return Response.ok(new Result(true)).cacheControl(NO_CACHE).build();
    }
    return Response.ok(new Result(false)).cacheControl(NO_CACHE).build();
}

This is the result of the Rest Call:

Rest service got called:Sat Apr 21 20:00:00 EDT 2018

Not sure if it has anything to do with timezone. My laptop is running in EST timezone.

like image 901
user_dev Avatar asked Mar 29 '26 17:03

user_dev


1 Answers

java.util.Date is the most confusing class in Java Core. I would not recommend to pass dates using java.util.Date, as it is intended to store both date and time.

As I pointed out in comments Apr 21 8pm EDT == Apr 22 midnight GMT. Print your date in GMT timezone and you will get Apr 22 00:00:00:

SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy hh:mm:ss a z");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Rest service got called:"+ sdf.format(demoBean.getDate()));

But I would rather recommend to send date as string or use java.time.LocalDate.

like image 172
hoaz Avatar answered Mar 31 '26 05:03

hoaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!