Java Date Time – How to build SpringBoot RestApi – Post/Get request with Java Date Time using Jackson and Make Query with Spring JPA example

spring-boot-rest-api-date-time-mysql-post-json-form-feature-image

[no_toc]
In the tutorial, we build a SpringBoot RestAPIs example that post/get data with java.util.Date time and save it to MySQL/PostgreSQL database using Spring JPA. Working with Java Date Time is an exciting part but also not easy task, fortunately we have the supporting from utilities of Jackson lib, now the job can be done in an easy way.

Let’s do details by steps!

Format Java Date Time with Jackson

Set the Format with @JsonFormat

With the @JsonFormat annotation of Jackson, we can use it to format a specific field in Java model:


public class DateTimeModel {	
    
    @JsonFormat(pattern="yyyy-MM-dd")
    private Date date;
    
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date datetime;
	
	...
}

Set TimeZone with @JsonFormat

For setting Time Zone, we use timezone attribute of the @JsonFormat:


@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="Europe/Paris")
private Date datetimewithzone;

Set Default Format

We can configure a default format & time-zone for all dates in application.properties:


spring.jackson.date-format=MM-dd-yyyy HH:mm:ss
spring.jackson.time-zone=Asia/Ho_Chi_Minh

Map Date and Time with Spring JPA

We use the @Temporal annotation to specify what the field represents. This annotation goes with a parameter having a value of TemporalType enum:


public enum TemporalType {

    /** Map as java.sql.Date */
    DATE, 

    /** Map as java.sql.Time */
    TIME, 

    /** Map as java.sql.Timestamp */
    TIMESTAMP
}

-> Now, our model will be like:


@Entity
@Table(name = "datetimemodel")
public class DateTimeModel {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;
	
    @Column	
    @Temporal(TemporalType.DATE)
    @JsonFormat(pattern="yyyy-MM-dd")
    private Date date;
    
    @Column
    @Temporal(TemporalType.TIMESTAMP)
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date datetime;
    
    @Column
    @Temporal(TemporalType.TIMESTAMP)
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="Europe/Paris")
    private Date datetimewithzone;
	
	...
}

Query the Entities with Date Time property from Database

For query data with Date Time property from database, we need to implement CrudRepository and use 2 approaches.

– Use the built-in rule of Spring JPA mechanics:


public interface DateTimeRepository extends CrudRepository{
	
	List findAllByDatetimeBetween(
								Date dateTimeStart,
								Date dateTimeEnd);
	
	...
}

– Use @Query annotation:


public interface DateTimeRepository extends CrudRepository{
	
	...
	
    @Query("select d from DateTimeModel d where d.datetime <= :datetime")
    List findAllWithDatetimeBefore(
    		@Param("datetime") Date datetime);			
}

RequestParam with Date Time in RestApi

For adding a request param with Date Time data type in RestAPI, we use @RequestParam & @DateTimeFormat


@GetMapping("/getallbydatetimebetween")
public List getAllByDatetimeBetween(
		@RequestParam("startdate") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date startdate,
		@RequestParam("enddate") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date enddate) {

	...
}

Practice

Create SpringBoot Project

We create a SpringBoot project as below structure:

spring-boot-rest-api-date-time-mysql-post-json-form-project-structure

– Dependencies List:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
</dependency>		
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>		
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>

Create Dates & Times Model

– Create DateTimeModel.java model:


package com.ozenero.datetimerestapi.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import com.fasterxml.jackson.annotation.JsonFormat;

@Entity
@Table(name = "datetimemodel")
public class DateTimeModel {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;
	
    @Column	
    @Temporal(TemporalType.DATE)
    @JsonFormat(pattern="yyyy-MM-dd")
    private Date date;
    
    @Column
    @Temporal(TemporalType.TIMESTAMP)
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date datetime;
    
    @Column
    @Temporal(TemporalType.TIMESTAMP)
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="Europe/Paris")
    private Date datetimewithzone;
    
    @Column
    @Temporal(TemporalType.TIMESTAMP)
    private Date defaultformatdatetime;
    
    public DateTimeModel() {}
    
    public DateTimeModel(Date date, Date datetime, Date datetimewithzone, Date defaultformatdatetime) {
    	this.date = date;
    	this.datetime = datetime;
    	this.datetimewithzone = datetimewithzone;
    	this.defaultformatdatetime = defaultformatdatetime;
    }
    
    // Getter/Setter date
    public void setDate(Date date) {
    	this.date = date;
    }
    
    public Date getDate() {
    	return this.date;
    }
    
    // Getter/Setter datetime
    public void setDatetime(Date datetime) {
    	this.datetime = datetime;
    }
    
    public Date getDatetime() {
    	return this.datetime;
    }
    
    // Getter/Setter datetimewithzone
    public void setDatetimewithzone(Date datetimewithzone) {
    	this.datetimewithzone = datetimewithzone;
    }
    
    public Date getDatetimewithzone() {
    	return this.datetimewithzone;
    }
    
    // Getter/Setter defaultformatdatetime
    public void setDefaultformatdatetime(Date defaultformatdatetime) {
    	this.defaultformatdatetime = defaultformatdatetime;
    }
    
    public Date getDefaultformatdatetime() {
    	return this.defaultformatdatetime;
    }
}

Create Repository

– Create DateTimeRepository.java repository:


package com.ozenero.datetimerestapi.repository;

import java.util.Date;
import java.util.List;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

import com.ozenero.datetimerestapi.model.DateTimeModel;

public interface DateTimeRepository extends CrudRepository{
	
	List findAllByDatetimeBetween(
								Date dateTimeStart,
								Date dateTimeEnd);
	
    @Query("select d from DateTimeModel d where d.datetime <= :datetime")
    List findAllWithDatetimeBefore(
    		@Param("datetime") Date datetime);
}

Create RestAPIs POST/GET/QUERY

– Create DateTimeController.java restapis:


package com.ozenero.datetimerestapi.controller;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ozenero.datetimerestapi.model.DateTimeModel;
import com.ozenero.datetimerestapi.repository.DateTimeRepository;

@RestController
@RequestMapping("/api")
public class DateTimeController {
	
	@Autowired
	DateTimeRepository dateTimeRepository;
	
	@GetMapping("/getdatetime")
	public Iterable getDateTimeModel() {
		return dateTimeRepository.findAll();
	}
	
	@PostMapping("/postdatetime")
	public String postDateTimeMode(@RequestBody DateTimeModel datetime) {
		dateTimeRepository.save(datetime);
		return "Done!";
	}
	
	@GetMapping("/getallbydatetimebetween")
	public List getAllByDatetimeBetween(
			@RequestParam("startdate") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date startdate,
			@RequestParam("enddate") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date enddate) {
		
		return dateTimeRepository.findAllByDatetimeBetween(startdate, enddate);
	}
	
	@GetMapping("/getallwithdatetimebefore")
	public List getAllWithDatetimeBefore(
			@RequestParam("datetime") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date datetime){

		return dateTimeRepository.findAllWithDatetimeBefore(datetime);
	}
}

Database Configuration

Config MySQL

application.properties:


spring.datasource.url=jdbc:mysql://localhost:3306/gkzdb
spring.datasource.username=root
spring.datasource.password=12345
spring.jpa.generate-ddl=true

spring.jackson.date-format=MM-dd-yyyy HH:mm:ss
spring.jackson.time-zone=Asia/Ho_Chi_Minh

Config PostgreSQL

application.properties:


spring.datasource.url=jdbc:postgresql://localhost/testdb
spring.datasource.username=postgres
spring.datasource.password=123
spring.jpa.generate-ddl=true

spring.jackson.date-format=MM-dd-yyyy HH:mm:ss
spring.jackson.time-zone=Asia/Ho_Chi_Minh

Run & Check Result

Run SpringBoot project, then makes requests.

– Post request:

spring-boot-rest-api-date-time-mysql-post-json-form

spring-boot-rest-api-date-time-mysql-post-json-form-records

spring-boot-rest-api-date-time-mysql-post-json-form-records-all-records

– Get All Entities request:

spring-boot-rest-api-date-time-mysql-post-json-form-get-all-request

– Query Request ->

+ Get Entities between 2 Date Time:

spring-boot-rest-api-date-time-mysql-post-json-form-get-date-time-between

+ Get Entities before a Date Time:

spring-boot-rest-api-date-time-mysql-post-json-form-get-all-days-before

Sourcecode

SpringBootRestApiDateTimeMySQL

Conclusion

Through the tutorial, We had learned how to create a SpringBoot RestAPI with Java Date Time data:

  • Using @JsonFormat annotation to format Date Time
  • Using @Temporal annotation to map Date and Time to work with Spring JPA
  • Query the Entities with Date Time property from Database
  • Format RequestParam with Date Time type in RestAPI by using @DateTimeFormat

Thank you for reading! See you next time!

43 thoughts on “Java Date Time – How to build SpringBoot RestApi – Post/Get request with Java Date Time using Jackson and Make Query with Spring JPA example”

  1. Hi , Its an awesome blog on DAte and time but I am confused in repository section. can u explain how it is implemented .
    i need further explanation in those 2 approaches used in DATETimeReposirory!

    Waiting for your reply!

  2. whoah this blog is great i like studying your articles. Stay up the good work! You know, a lot of persons are hunting around for this information, you can help them greatly.

  3. Hmm is anyone else encountering problems with the images on this blog loading? I’m trying to figure out if its a problem on my end or if it’s the blog. Any feed-back would be greatly appreciated.

  4. 74221 720972Your home is valueble for me. Thanks!? This internet page is actually a walk-via for all with the information you necessary about this and didn know who to ask. Glimpse proper here, and you l surely uncover it. 580167

  5. What i do not understood is actually how you’re not really much more well-liked than you might be now. You’re very intelligent. You realize thus considerably relating to this subject, made me personally consider it from numerous varied angles. Its like men and women aren’t fascinated unless it抯 one thing to do with Lady gaga! Your own stuffs great. Always maintain it up!

  6. I have observed that in the world these days, video games will be the latest rage with kids of all ages. Often times it may be impossible to drag your family away from the activities. If you want the best of both worlds, there are numerous educational video games for kids. Thanks for your post.

  7. 60883 583228An intriguing discussion will probably be worth comment. I feel which you simply write much more about this topic, it may possibly become a taboo subject but usually consumers are inadequate to communicate in on such topics. To another. Cheers 974867

  8. I have really learned some new things by means of your weblog. One other thing I’d like to say is always that newer laptop or computer os’s often allow a lot more memory for use, but they furthermore demand more memory space simply to function. If your computer can not handle extra memory as well as newest software requires that memory increase, it usually is the time to buy a new Computer system. Thanks

  9. One thing is the fact that one of the most popular incentives for utilizing your credit cards is a cash-back or even rebate supply. Generally, you’ll have access to 1-5 back in various expenditures. Depending on the card, you may get 1 in return on most purchases, and 5 back on expenses made on convenience stores, gasoline stations, grocery stores in addition to ‘member merchants’.

  10. Hey very cool web site!! Man .. Excellent .. Amazing .. I will bookmark your I’m happy to find a lot of useful information here in the post, we need work out more strategies in this regard, thanks for sharing. . . . . .

  11. Aw, this was a really nice post. In concept I want to put in writing like this additionally ?taking time and precise effort to make an excellent article?but what can I say?I procrastinate alot and certainly not appear to get one thing done.

  12. Howdy just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Firefox. I’m not sure if this is a formatting issue or something to do with internet browser compatibility but I figured I’d post to let you know. The design and style look great though! Hope you get the problem fixed soon. Many thanks

  13. Great ?I should certainly pronounce, impressed with your website. I had no trouble navigating through all tabs as well as related information ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, site theme . a tones way for your customer to communicate. Excellent task..

  14. hello there and thank you to your info ?I抳e certainly picked up anything new from right here. I did alternatively expertise several technical issues the use of this site, since I skilled to reload the website lots of occasions prior to I may get it to load correctly. I were brooding about in case your web host is OK? Now not that I am complaining, however sluggish loading circumstances instances will sometimes affect your placement in google and can damage your high-quality rating if advertising and ***********|advertising|advertising|advertising and *********** with Adwords. Well I抦 adding this RSS to my email and can look out for much extra of your respective intriguing content. Make sure you replace this once more soon..

  15. Hey there, I think your website might be having browser compatibility issues. When I look at your blog in Opera, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, wonderful blog!

  16. Thank you for any other great article. Where else may anybody get that type of info in such a perfect manner of writing? I’ve a presentation next week, and I am at the search for such information.

  17. Great post. I was checking continuously this blog and I’m impressed! Very useful info specifically the last part 🙂 I care for such info much. I was seeking this certain information for a long time. Thank you and best of luck.

  18. I feel this is one of the so much important information for me.
    And i am happy studying your article. However want
    to observation on few normal issues, The website taste is perfect, the articles is really great : D.
    Good task, cheers

  19. When I initially commented I clicked the “Notify me when new comments are added”
    checkbox and now each time a comment is added I get several e-mails with
    the same comment. Is there any way you can remove people from
    that service? Bless you!

  20. Hi there, I believe your web site may be having web browser compatibility issues. Whenever I look at your blog in Safari, it looks fine however when opening in I.E., it’s got some overlapping issues. I merely wanted to give you a quick heads up! Aside from that, great website!

  21. Thank you a lot for sharing this with all of us you really know what you are speaking about!
    Bookmarked. Kindly additionally consult with my web site =).
    We can have a link alternate agreement among us

  22. Hi there exceptional blog! Does running a blog such as
    this take a great deal of work? I have absolutely no
    understanding of coding however I was hoping to start my
    own blog soon. Anyhow, should you have any suggestions or tips for new blog owners please share.
    I understand this is off subject nevertheless I simply had to ask.
    Cheers!

  23. 638123 393593Chaga mushroom tea leaf is thought-about any adverse health elixir at Spain, Siberia and a lot of n . Countries in europe sadly contains before you go ahead significantly avoidable the main limelight under western culture. Mushroom 425404

  24. Howdy! I know this is kinda off topic but I was wondering if you knew where I could find a captcha plugin for my
    comment form? I’m using the same blog platform
    as yours and I’m having problems finding one?
    Thanks a lot!

Leave a Reply

Your email address will not be published. Required fields are marked *