Problem with timezone in Json response from SpringSpring Boot Jackson date and timestamp Formathow to pass date yyyy-mm-dd in spring boot controller request body when default timestamp format set to something elseDate is getting converted to Long while making a rest call using springFacing issue with jackson date converstionCreate ArrayList from arrayHow do I format a Microsoft JSON date?Can comments be used in JSON?How can I pretty-print JSON in a shell script?What is the correct JSON content type?Why does Google prepend while(1); to their JSON responses?How can I pretty-print JSON using JavaScript?Parse JSON in JavaScript?What's the difference between @Component, @Repository & @Service annotations in Spring?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?

Is refusing to concede in the face of an unstoppable Nexus combo punishable?

Ask for a paid taxi in order to arrive as early as possible for an interview within the city

Why don't sharp and flat root note chords seem to be present in much guitar music?

Why didn’t Doctor Strange stay in the original winning timeline?

How to organize ideas to start writing a novel?

The teacher logged me in as administrator for doing a short task, is the whole system now compromised?

How to compare two different formulations of a problem?

Why don't we use Cavea-B

What is the evidence on the danger of feeding whole blueberries and grapes to infants and toddlers?

How to avoid using System.String with Rfc2898DeriveBytes in C#

Ruling for Grappling a Creature Underwater While you are on Land?

Can you be convicted for being a murderer twice?

Metal that glows when near pieces of itself

Sleeping solo in a double sleeping bag

Is there a known non-euclidean geometry where two concentric circles of different radii can intersect? (as in the novel "The Universe Between")

Is it appropriate for a prospective landlord to ask me for my credit report?

Was Switzerland really impossible to invade during WW2?

Was 'help' pronounced starting with a vowel sound?

Is there a SubImageApply?

How did Apollo 15's depressurization work?

Can pay be witheld for hours cleaning up after closing time?

Was this pillow joke on Friends intentional or a mistake?

Church Booleans

Are required indicators necessary for radio buttons?



Problem with timezone in Json response from Spring


Spring Boot Jackson date and timestamp Formathow to pass date yyyy-mm-dd in spring boot controller request body when default timestamp format set to something elseDate is getting converted to Long while making a rest call using springFacing issue with jackson date converstionCreate ArrayList from arrayHow do I format a Microsoft JSON date?Can comments be used in JSON?How can I pretty-print JSON in a shell script?What is the correct JSON content type?Why does Google prepend while(1); to their JSON responses?How can I pretty-print JSON using JavaScript?Parse JSON in JavaScript?What's the difference between @Component, @Repository & @Service annotations in Spring?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have a problem with displaying dates in JSON output. In code I use java.util.Date and its value is 2019-03-07 but in JSON I got 2019-03-06 23:00:00. I think the problem is in timezone, but I don't use timezones in DB and in code too.



I was trying to fix it with



@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss", timezone="UTC")



and



@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss", timezone="Europe/Warsaw")



The first didn't help, the second helped but I don't accept this solution.



Part of my controller:



return new ThisDay(
sysoperMgr.getToday(),
new Date()
);


This is object which I return.



@Getter
@Setter
public class ThisDay

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
Date dataZamkniecia;

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
Date dataSystemowa;

public BiezacaDoba(Date dataZamkniecia, Date dataSystemowa)
this.dataZamkniecia = dataZamkniecia; // cdate = 2019-03-07T00:00:00.000+0100
this.dataSystemowa = dataSystemowa; // cdate = 2019-03-27T16:08:12.343+0100




This function gets date:



public Date getToday() 

Timestamp timestamp = sysoperDao.getDataOstatniejZamknietejDoby(); // cdate = 2019-03-06T00:00:00.000+0100
java.util.Date lastDay = new java.sql.Date(misc.roundTimestamp(timestamp).getTime()); // cdate = 2019-03-06T00:00:00.000+0100
java.util.Date thisDay = misc.incrementDate(ostatniaDoba, Increment.DAILY, 1); // cdate = 2019-03-07T00:00:00.000+0100
return thisDay;



Json result:




"dataZamkniecia":"2019-03-06 23:00:00",
"dataSystemowa": "2019-03-27 15:12:15"



How do yo get the JSON to display the date always in the local timezone?










share|improve this question


























  • Jackson does use the local time zone unless configured otherwise. Try it with a small standalone program. Your issue comes from whatever surrounds the small part you're talking about. You'll need to give details about your application in its entirety, and the frameworks you're using.

    – kumesana
    Mar 27 at 15:49











  • Is there a reason why you've chosen the legacy java.util.Date type? It is long since replaced by the java.time.* types. programminghints.com/2017/05/still-using-java-util-date-dont

    – Matt Johnson-Pint
    Mar 27 at 17:13











  • @MattJohnson I use java.util.Date because in entities there are Dates from java.sql and converson between java.util.Date and java.sql.Date is simple. The second argument is that in my database dates are saved without timezone and I don't think that adding this function in my DB (Firebird) is now possible. Do you think in this situation I should use java.time.* instead java.util.Date?? What with entities, as I know JDBC uses java.sql.Date?

    – Olek
    Mar 30 at 14:59

















0















I have a problem with displaying dates in JSON output. In code I use java.util.Date and its value is 2019-03-07 but in JSON I got 2019-03-06 23:00:00. I think the problem is in timezone, but I don't use timezones in DB and in code too.



I was trying to fix it with



@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss", timezone="UTC")



and



@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss", timezone="Europe/Warsaw")



The first didn't help, the second helped but I don't accept this solution.



Part of my controller:



return new ThisDay(
sysoperMgr.getToday(),
new Date()
);


This is object which I return.



@Getter
@Setter
public class ThisDay

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
Date dataZamkniecia;

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
Date dataSystemowa;

public BiezacaDoba(Date dataZamkniecia, Date dataSystemowa)
this.dataZamkniecia = dataZamkniecia; // cdate = 2019-03-07T00:00:00.000+0100
this.dataSystemowa = dataSystemowa; // cdate = 2019-03-27T16:08:12.343+0100




This function gets date:



public Date getToday() 

Timestamp timestamp = sysoperDao.getDataOstatniejZamknietejDoby(); // cdate = 2019-03-06T00:00:00.000+0100
java.util.Date lastDay = new java.sql.Date(misc.roundTimestamp(timestamp).getTime()); // cdate = 2019-03-06T00:00:00.000+0100
java.util.Date thisDay = misc.incrementDate(ostatniaDoba, Increment.DAILY, 1); // cdate = 2019-03-07T00:00:00.000+0100
return thisDay;



Json result:




"dataZamkniecia":"2019-03-06 23:00:00",
"dataSystemowa": "2019-03-27 15:12:15"



How do yo get the JSON to display the date always in the local timezone?










share|improve this question


























  • Jackson does use the local time zone unless configured otherwise. Try it with a small standalone program. Your issue comes from whatever surrounds the small part you're talking about. You'll need to give details about your application in its entirety, and the frameworks you're using.

    – kumesana
    Mar 27 at 15:49











  • Is there a reason why you've chosen the legacy java.util.Date type? It is long since replaced by the java.time.* types. programminghints.com/2017/05/still-using-java-util-date-dont

    – Matt Johnson-Pint
    Mar 27 at 17:13











  • @MattJohnson I use java.util.Date because in entities there are Dates from java.sql and converson between java.util.Date and java.sql.Date is simple. The second argument is that in my database dates are saved without timezone and I don't think that adding this function in my DB (Firebird) is now possible. Do you think in this situation I should use java.time.* instead java.util.Date?? What with entities, as I know JDBC uses java.sql.Date?

    – Olek
    Mar 30 at 14:59













0












0








0








I have a problem with displaying dates in JSON output. In code I use java.util.Date and its value is 2019-03-07 but in JSON I got 2019-03-06 23:00:00. I think the problem is in timezone, but I don't use timezones in DB and in code too.



I was trying to fix it with



@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss", timezone="UTC")



and



@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss", timezone="Europe/Warsaw")



The first didn't help, the second helped but I don't accept this solution.



Part of my controller:



return new ThisDay(
sysoperMgr.getToday(),
new Date()
);


This is object which I return.



@Getter
@Setter
public class ThisDay

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
Date dataZamkniecia;

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
Date dataSystemowa;

public BiezacaDoba(Date dataZamkniecia, Date dataSystemowa)
this.dataZamkniecia = dataZamkniecia; // cdate = 2019-03-07T00:00:00.000+0100
this.dataSystemowa = dataSystemowa; // cdate = 2019-03-27T16:08:12.343+0100




This function gets date:



public Date getToday() 

Timestamp timestamp = sysoperDao.getDataOstatniejZamknietejDoby(); // cdate = 2019-03-06T00:00:00.000+0100
java.util.Date lastDay = new java.sql.Date(misc.roundTimestamp(timestamp).getTime()); // cdate = 2019-03-06T00:00:00.000+0100
java.util.Date thisDay = misc.incrementDate(ostatniaDoba, Increment.DAILY, 1); // cdate = 2019-03-07T00:00:00.000+0100
return thisDay;



Json result:




"dataZamkniecia":"2019-03-06 23:00:00",
"dataSystemowa": "2019-03-27 15:12:15"



How do yo get the JSON to display the date always in the local timezone?










share|improve this question
















I have a problem with displaying dates in JSON output. In code I use java.util.Date and its value is 2019-03-07 but in JSON I got 2019-03-06 23:00:00. I think the problem is in timezone, but I don't use timezones in DB and in code too.



I was trying to fix it with



@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss", timezone="UTC")



and



@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss", timezone="Europe/Warsaw")



The first didn't help, the second helped but I don't accept this solution.



Part of my controller:



return new ThisDay(
sysoperMgr.getToday(),
new Date()
);


This is object which I return.



@Getter
@Setter
public class ThisDay

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
Date dataZamkniecia;

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
Date dataSystemowa;

public BiezacaDoba(Date dataZamkniecia, Date dataSystemowa)
this.dataZamkniecia = dataZamkniecia; // cdate = 2019-03-07T00:00:00.000+0100
this.dataSystemowa = dataSystemowa; // cdate = 2019-03-27T16:08:12.343+0100




This function gets date:



public Date getToday() 

Timestamp timestamp = sysoperDao.getDataOstatniejZamknietejDoby(); // cdate = 2019-03-06T00:00:00.000+0100
java.util.Date lastDay = new java.sql.Date(misc.roundTimestamp(timestamp).getTime()); // cdate = 2019-03-06T00:00:00.000+0100
java.util.Date thisDay = misc.incrementDate(ostatniaDoba, Increment.DAILY, 1); // cdate = 2019-03-07T00:00:00.000+0100
return thisDay;



Json result:




"dataZamkniecia":"2019-03-06 23:00:00",
"dataSystemowa": "2019-03-27 15:12:15"



How do yo get the JSON to display the date always in the local timezone?







java json spring timezone






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 15:53









PaulNUK

2,38616 silver badges33 bronze badges




2,38616 silver badges33 bronze badges










asked Mar 27 at 15:28









OlekOlek

668 bronze badges




668 bronze badges















  • Jackson does use the local time zone unless configured otherwise. Try it with a small standalone program. Your issue comes from whatever surrounds the small part you're talking about. You'll need to give details about your application in its entirety, and the frameworks you're using.

    – kumesana
    Mar 27 at 15:49











  • Is there a reason why you've chosen the legacy java.util.Date type? It is long since replaced by the java.time.* types. programminghints.com/2017/05/still-using-java-util-date-dont

    – Matt Johnson-Pint
    Mar 27 at 17:13











  • @MattJohnson I use java.util.Date because in entities there are Dates from java.sql and converson between java.util.Date and java.sql.Date is simple. The second argument is that in my database dates are saved without timezone and I don't think that adding this function in my DB (Firebird) is now possible. Do you think in this situation I should use java.time.* instead java.util.Date?? What with entities, as I know JDBC uses java.sql.Date?

    – Olek
    Mar 30 at 14:59

















  • Jackson does use the local time zone unless configured otherwise. Try it with a small standalone program. Your issue comes from whatever surrounds the small part you're talking about. You'll need to give details about your application in its entirety, and the frameworks you're using.

    – kumesana
    Mar 27 at 15:49











  • Is there a reason why you've chosen the legacy java.util.Date type? It is long since replaced by the java.time.* types. programminghints.com/2017/05/still-using-java-util-date-dont

    – Matt Johnson-Pint
    Mar 27 at 17:13











  • @MattJohnson I use java.util.Date because in entities there are Dates from java.sql and converson between java.util.Date and java.sql.Date is simple. The second argument is that in my database dates are saved without timezone and I don't think that adding this function in my DB (Firebird) is now possible. Do you think in this situation I should use java.time.* instead java.util.Date?? What with entities, as I know JDBC uses java.sql.Date?

    – Olek
    Mar 30 at 14:59
















Jackson does use the local time zone unless configured otherwise. Try it with a small standalone program. Your issue comes from whatever surrounds the small part you're talking about. You'll need to give details about your application in its entirety, and the frameworks you're using.

– kumesana
Mar 27 at 15:49





Jackson does use the local time zone unless configured otherwise. Try it with a small standalone program. Your issue comes from whatever surrounds the small part you're talking about. You'll need to give details about your application in its entirety, and the frameworks you're using.

– kumesana
Mar 27 at 15:49













Is there a reason why you've chosen the legacy java.util.Date type? It is long since replaced by the java.time.* types. programminghints.com/2017/05/still-using-java-util-date-dont

– Matt Johnson-Pint
Mar 27 at 17:13





Is there a reason why you've chosen the legacy java.util.Date type? It is long since replaced by the java.time.* types. programminghints.com/2017/05/still-using-java-util-date-dont

– Matt Johnson-Pint
Mar 27 at 17:13













@MattJohnson I use java.util.Date because in entities there are Dates from java.sql and converson between java.util.Date and java.sql.Date is simple. The second argument is that in my database dates are saved without timezone and I don't think that adding this function in my DB (Firebird) is now possible. Do you think in this situation I should use java.time.* instead java.util.Date?? What with entities, as I know JDBC uses java.sql.Date?

– Olek
Mar 30 at 14:59





@MattJohnson I use java.util.Date because in entities there are Dates from java.sql and converson between java.util.Date and java.sql.Date is simple. The second argument is that in my database dates are saved without timezone and I don't think that adding this function in my DB (Firebird) is now possible. Do you think in this situation I should use java.time.* instead java.util.Date?? What with entities, as I know JDBC uses java.sql.Date?

– Olek
Mar 30 at 14:59












1 Answer
1






active

oldest

votes


















3














Date is outdated class and should not be used since Java 8 released java.time package or we can use Joda-Time. You are converting date from Timestamp to java.sql.Date and later to java.util.Date. This is very unsafe, see below example:



import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class JsonApp

public static void main(String[] args) throws Exception
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);

// Java time precise dates
LocalDate localDateOpened = LocalDate.of(2019, 03, 07);
LocalDate localDateClosed = localDateOpened.plusDays(20);

ZoneId utc = ZoneId.of("UTC");
Date opened = Date.from(localDateOpened.atStartOfDay(utc).toInstant());
Date closed = Date.from(localDateClosed.atStartOfDay(utc).toInstant());

System.out.println("Dates generated from java.time.*");
System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));

// Calculate dates with default timezone
Calendar calendar = Calendar.getInstance();
opened = calendar.getTime();
calendar.add(Calendar.DAY_OF_MONTH, 20);
closed = calendar.getTime();

System.out.println("Dates generated from Calendar");
System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));

// Calculate dates with UTC timezone
calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone(utc));
calendar.set(Calendar.MILLISECOND, 0); // Recompute

opened = calendar.getTime();
calendar.add(Calendar.DAY_OF_MONTH, 20);
closed = calendar.getTime();

System.out.println("Dates generated from UTC Calendar");
System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));



class ThisDay

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date opened;

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date closed;

public ThisDay(Date opened, Date closed)
this.opened = opened;
this.closed = closed;


public Date getOpened()
return opened;


public void setOpened(Date opened)
this.opened = opened;


public Date getClosed()
return closed;


public void setClosed(Date closed)
this.closed = closed;




Above code prints:



Dates generated from java.time.*

"opened" : "2019-03-07 00:00:00",
"closed" : "2019-03-27 00:00:00"

Dates generated from Calendar

"opened" : "2019-03-27 23:45:12",
"closed" : "2019-04-16 22:45:12"

Dates generated from UTC Calendar

"opened" : "2019-03-28 00:45:12",
"closed" : "2019-04-17 00:45:12"



Notice that second and third opened dates has difference one hour. I manually set calendar timezone to UTC and force to recompute values setting milliseconds to 0:



calendar.setTimeZone(TimeZone.getTimeZone(utc));
calendar.set(Calendar.MILLISECOND, 0); // Recompute


This is why Date is outdated and java.time package should be used. If you do not want to show time, only date - change format to @JsonFormat(pattern = "yyyy-MM-dd").



See also:



  • Spring Boot Jackson date and timestamp Format





share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55380919%2fproblem-with-timezone-in-json-response-from-spring%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    Date is outdated class and should not be used since Java 8 released java.time package or we can use Joda-Time. You are converting date from Timestamp to java.sql.Date and later to java.util.Date. This is very unsafe, see below example:



    import com.fasterxml.jackson.annotation.JsonFormat;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;

    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.TimeZone;

    public class JsonApp

    public static void main(String[] args) throws Exception
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    // Java time precise dates
    LocalDate localDateOpened = LocalDate.of(2019, 03, 07);
    LocalDate localDateClosed = localDateOpened.plusDays(20);

    ZoneId utc = ZoneId.of("UTC");
    Date opened = Date.from(localDateOpened.atStartOfDay(utc).toInstant());
    Date closed = Date.from(localDateClosed.atStartOfDay(utc).toInstant());

    System.out.println("Dates generated from java.time.*");
    System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));

    // Calculate dates with default timezone
    Calendar calendar = Calendar.getInstance();
    opened = calendar.getTime();
    calendar.add(Calendar.DAY_OF_MONTH, 20);
    closed = calendar.getTime();

    System.out.println("Dates generated from Calendar");
    System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));

    // Calculate dates with UTC timezone
    calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone(utc));
    calendar.set(Calendar.MILLISECOND, 0); // Recompute

    opened = calendar.getTime();
    calendar.add(Calendar.DAY_OF_MONTH, 20);
    closed = calendar.getTime();

    System.out.println("Dates generated from UTC Calendar");
    System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));



    class ThisDay

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date opened;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date closed;

    public ThisDay(Date opened, Date closed)
    this.opened = opened;
    this.closed = closed;


    public Date getOpened()
    return opened;


    public void setOpened(Date opened)
    this.opened = opened;


    public Date getClosed()
    return closed;


    public void setClosed(Date closed)
    this.closed = closed;




    Above code prints:



    Dates generated from java.time.*

    "opened" : "2019-03-07 00:00:00",
    "closed" : "2019-03-27 00:00:00"

    Dates generated from Calendar

    "opened" : "2019-03-27 23:45:12",
    "closed" : "2019-04-16 22:45:12"

    Dates generated from UTC Calendar

    "opened" : "2019-03-28 00:45:12",
    "closed" : "2019-04-17 00:45:12"



    Notice that second and third opened dates has difference one hour. I manually set calendar timezone to UTC and force to recompute values setting milliseconds to 0:



    calendar.setTimeZone(TimeZone.getTimeZone(utc));
    calendar.set(Calendar.MILLISECOND, 0); // Recompute


    This is why Date is outdated and java.time package should be used. If you do not want to show time, only date - change format to @JsonFormat(pattern = "yyyy-MM-dd").



    See also:



    • Spring Boot Jackson date and timestamp Format





    share|improve this answer





























      3














      Date is outdated class and should not be used since Java 8 released java.time package or we can use Joda-Time. You are converting date from Timestamp to java.sql.Date and later to java.util.Date. This is very unsafe, see below example:



      import com.fasterxml.jackson.annotation.JsonFormat;
      import com.fasterxml.jackson.databind.ObjectMapper;
      import com.fasterxml.jackson.databind.SerializationFeature;

      import java.time.LocalDate;
      import java.time.ZoneId;
      import java.util.Calendar;
      import java.util.Date;
      import java.util.TimeZone;

      public class JsonApp

      public static void main(String[] args) throws Exception
      ObjectMapper mapper = new ObjectMapper();
      mapper.enable(SerializationFeature.INDENT_OUTPUT);

      // Java time precise dates
      LocalDate localDateOpened = LocalDate.of(2019, 03, 07);
      LocalDate localDateClosed = localDateOpened.plusDays(20);

      ZoneId utc = ZoneId.of("UTC");
      Date opened = Date.from(localDateOpened.atStartOfDay(utc).toInstant());
      Date closed = Date.from(localDateClosed.atStartOfDay(utc).toInstant());

      System.out.println("Dates generated from java.time.*");
      System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));

      // Calculate dates with default timezone
      Calendar calendar = Calendar.getInstance();
      opened = calendar.getTime();
      calendar.add(Calendar.DAY_OF_MONTH, 20);
      closed = calendar.getTime();

      System.out.println("Dates generated from Calendar");
      System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));

      // Calculate dates with UTC timezone
      calendar = Calendar.getInstance();
      calendar.setTimeZone(TimeZone.getTimeZone(utc));
      calendar.set(Calendar.MILLISECOND, 0); // Recompute

      opened = calendar.getTime();
      calendar.add(Calendar.DAY_OF_MONTH, 20);
      closed = calendar.getTime();

      System.out.println("Dates generated from UTC Calendar");
      System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));



      class ThisDay

      @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
      private Date opened;

      @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
      private Date closed;

      public ThisDay(Date opened, Date closed)
      this.opened = opened;
      this.closed = closed;


      public Date getOpened()
      return opened;


      public void setOpened(Date opened)
      this.opened = opened;


      public Date getClosed()
      return closed;


      public void setClosed(Date closed)
      this.closed = closed;




      Above code prints:



      Dates generated from java.time.*

      "opened" : "2019-03-07 00:00:00",
      "closed" : "2019-03-27 00:00:00"

      Dates generated from Calendar

      "opened" : "2019-03-27 23:45:12",
      "closed" : "2019-04-16 22:45:12"

      Dates generated from UTC Calendar

      "opened" : "2019-03-28 00:45:12",
      "closed" : "2019-04-17 00:45:12"



      Notice that second and third opened dates has difference one hour. I manually set calendar timezone to UTC and force to recompute values setting milliseconds to 0:



      calendar.setTimeZone(TimeZone.getTimeZone(utc));
      calendar.set(Calendar.MILLISECOND, 0); // Recompute


      This is why Date is outdated and java.time package should be used. If you do not want to show time, only date - change format to @JsonFormat(pattern = "yyyy-MM-dd").



      See also:



      • Spring Boot Jackson date and timestamp Format





      share|improve this answer



























        3












        3








        3







        Date is outdated class and should not be used since Java 8 released java.time package or we can use Joda-Time. You are converting date from Timestamp to java.sql.Date and later to java.util.Date. This is very unsafe, see below example:



        import com.fasterxml.jackson.annotation.JsonFormat;
        import com.fasterxml.jackson.databind.ObjectMapper;
        import com.fasterxml.jackson.databind.SerializationFeature;

        import java.time.LocalDate;
        import java.time.ZoneId;
        import java.util.Calendar;
        import java.util.Date;
        import java.util.TimeZone;

        public class JsonApp

        public static void main(String[] args) throws Exception
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        // Java time precise dates
        LocalDate localDateOpened = LocalDate.of(2019, 03, 07);
        LocalDate localDateClosed = localDateOpened.plusDays(20);

        ZoneId utc = ZoneId.of("UTC");
        Date opened = Date.from(localDateOpened.atStartOfDay(utc).toInstant());
        Date closed = Date.from(localDateClosed.atStartOfDay(utc).toInstant());

        System.out.println("Dates generated from java.time.*");
        System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));

        // Calculate dates with default timezone
        Calendar calendar = Calendar.getInstance();
        opened = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, 20);
        closed = calendar.getTime();

        System.out.println("Dates generated from Calendar");
        System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));

        // Calculate dates with UTC timezone
        calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone(utc));
        calendar.set(Calendar.MILLISECOND, 0); // Recompute

        opened = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, 20);
        closed = calendar.getTime();

        System.out.println("Dates generated from UTC Calendar");
        System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));



        class ThisDay

        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date opened;

        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date closed;

        public ThisDay(Date opened, Date closed)
        this.opened = opened;
        this.closed = closed;


        public Date getOpened()
        return opened;


        public void setOpened(Date opened)
        this.opened = opened;


        public Date getClosed()
        return closed;


        public void setClosed(Date closed)
        this.closed = closed;




        Above code prints:



        Dates generated from java.time.*

        "opened" : "2019-03-07 00:00:00",
        "closed" : "2019-03-27 00:00:00"

        Dates generated from Calendar

        "opened" : "2019-03-27 23:45:12",
        "closed" : "2019-04-16 22:45:12"

        Dates generated from UTC Calendar

        "opened" : "2019-03-28 00:45:12",
        "closed" : "2019-04-17 00:45:12"



        Notice that second and third opened dates has difference one hour. I manually set calendar timezone to UTC and force to recompute values setting milliseconds to 0:



        calendar.setTimeZone(TimeZone.getTimeZone(utc));
        calendar.set(Calendar.MILLISECOND, 0); // Recompute


        This is why Date is outdated and java.time package should be used. If you do not want to show time, only date - change format to @JsonFormat(pattern = "yyyy-MM-dd").



        See also:



        • Spring Boot Jackson date and timestamp Format





        share|improve this answer













        Date is outdated class and should not be used since Java 8 released java.time package or we can use Joda-Time. You are converting date from Timestamp to java.sql.Date and later to java.util.Date. This is very unsafe, see below example:



        import com.fasterxml.jackson.annotation.JsonFormat;
        import com.fasterxml.jackson.databind.ObjectMapper;
        import com.fasterxml.jackson.databind.SerializationFeature;

        import java.time.LocalDate;
        import java.time.ZoneId;
        import java.util.Calendar;
        import java.util.Date;
        import java.util.TimeZone;

        public class JsonApp

        public static void main(String[] args) throws Exception
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        // Java time precise dates
        LocalDate localDateOpened = LocalDate.of(2019, 03, 07);
        LocalDate localDateClosed = localDateOpened.plusDays(20);

        ZoneId utc = ZoneId.of("UTC");
        Date opened = Date.from(localDateOpened.atStartOfDay(utc).toInstant());
        Date closed = Date.from(localDateClosed.atStartOfDay(utc).toInstant());

        System.out.println("Dates generated from java.time.*");
        System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));

        // Calculate dates with default timezone
        Calendar calendar = Calendar.getInstance();
        opened = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, 20);
        closed = calendar.getTime();

        System.out.println("Dates generated from Calendar");
        System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));

        // Calculate dates with UTC timezone
        calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone(utc));
        calendar.set(Calendar.MILLISECOND, 0); // Recompute

        opened = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, 20);
        closed = calendar.getTime();

        System.out.println("Dates generated from UTC Calendar");
        System.out.println(mapper.writeValueAsString(new ThisDay(opened, closed)));



        class ThisDay

        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date opened;

        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date closed;

        public ThisDay(Date opened, Date closed)
        this.opened = opened;
        this.closed = closed;


        public Date getOpened()
        return opened;


        public void setOpened(Date opened)
        this.opened = opened;


        public Date getClosed()
        return closed;


        public void setClosed(Date closed)
        this.closed = closed;




        Above code prints:



        Dates generated from java.time.*

        "opened" : "2019-03-07 00:00:00",
        "closed" : "2019-03-27 00:00:00"

        Dates generated from Calendar

        "opened" : "2019-03-27 23:45:12",
        "closed" : "2019-04-16 22:45:12"

        Dates generated from UTC Calendar

        "opened" : "2019-03-28 00:45:12",
        "closed" : "2019-04-17 00:45:12"



        Notice that second and third opened dates has difference one hour. I manually set calendar timezone to UTC and force to recompute values setting milliseconds to 0:



        calendar.setTimeZone(TimeZone.getTimeZone(utc));
        calendar.set(Calendar.MILLISECOND, 0); // Recompute


        This is why Date is outdated and java.time package should be used. If you do not want to show time, only date - change format to @JsonFormat(pattern = "yyyy-MM-dd").



        See also:



        • Spring Boot Jackson date and timestamp Format






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 27 at 23:52









        Michał ZioberMichał Ziober

        19.7k13 gold badges76 silver badges113 bronze badges




        19.7k13 gold badges76 silver badges113 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55380919%2fproblem-with-timezone-in-json-response-from-spring%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현