SpringBoot,Sring MVC日期格式处理总结

一、日期格式化相关知识

1、JDK1.8之前

//日期转换成字符串
    public static String dateToString(Date date, String patt) {
        SimpleDateFormat sdf = new SimpleDateFormat(patt);
        String format = sdf.format(date);
        return format;
    }

    //字符串转换成日期
    public static Date string2Date(String str, String patt) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(patt);
        Date parse = sdf.parse(str);
        return parse;
    }

2、JDK1.8

新的时间API

2.1、DateTimeFormatter
@Test
    public void test(){
        //方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");        //自定义格式
        DateTimeFormatter formatter1 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //格式化:日期-->字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = formatter.format(localDateTime);
        System.out.println(localDateTime);
        System.out.println(str1);//2019-02-18T15:42:18.797 //2021-06-21 22:01:07
    }

      //解析:字符串 -->日期
        TemporalAccessor parse = formatter.parse("2021-06-21 22:01:07");
        System.out.println(parse);

优化写法

    @Test
    public void test1(){
        //方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");         //自定义格式
        DateTimeFormatter formatter1 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //格式化:日期-->字符串
        
        //格式1: 2021-06-21 22:13:54
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = localDateTime.format(formatter);
        System.out.println(str1);  //2021-06-21 22:13:54
       
        //格式2: 2021年6月21日 下午10时13分54秒
        String format =              localDateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG));
        System.out.println(format); //2021年6月21日 下午10时13分54秒

        //解析:字符串 -->日期
        LocalDateTime dateTime = LocalDateTime.parse(str1,formatter);
        System.out.println(dateTime); //2021-06-21T22:10:10
    }

其他格式化类型

@Test
    public void test3(){
        //方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //格式化:日期-->字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = formatter.format(localDateTime);
        System.out.println(localDateTime);
        System.out.println(str1);//2019-02-18T15:42:18.797

        //解析:字符串 -->日期
        TemporalAccessor parse = formatter.parse("2019-02-18T15:42:18.797");
        System.out.println(parse);

        //方式二:
        //本地化相关的格式。如:ofLocalizedDateTime()
        //FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        //格式化
        String str2 = formatter1.format(localDateTime);
        System.out.println(str2);//2019年2月18日 下午03时47分16秒


//      本地化相关的格式。如:ofLocalizedDate()
//      FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
        //格式化
        String str3 = formatter2.format(LocalDate.now());
        System.out.println(str3);//2019-2-18


//       重点: 方式三:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //格式化
        String str4 = formatter3.format(LocalDateTime.now());
        System.out.println(str4);//2019-02-18 03:52:09

        //解析
        TemporalAccessor accessor = formatter3.parse("2019-02-18 03:52:09");
        System.out.println(accessor);

    }

二、 自定义类型转换器

1、Spring MVC 自定义类型转换器

  1. 表单提交的任何数据类型全部都是字符串类型,但是后台定义Integer类型,数据也可以封装上,说明

Spring框架内部会默认进行数据类型转换。

  1. 如果想自定义数据类型转换,可以实现Converter的接口

  2. 自定义类型转换器

package cn.itcast.utils;

import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date;

import org.springframework.core.convert.converter.Converter;

/**
*把字符串转换成日期的转换器
*@author rt
*/
public class StringToDateConverter implements Converter<String, Date>{

    /**
     * 进行类型转换的方法
     */
    public Date convert(String source) {
    // 判 断
        if(source == null) {
            throw new RuntimeException("参数不能为空");

        }
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
     // 解析字符串
            Date date = df.parse(source); return date;
        } catch (Exception e) {
            throw new RuntimeException("类型转换错误");
        }
    }
}

2、SpringBoot自定义类型转换器

boot1.xx版本代码

2.1 String类型转换为Date类型

​ 继承Spring提供的org.springframework.core.convert.converter.Converter对象,重写其中的convert()方法 其中是自己的转换逻辑。

/**
 * 将String 转换为Date集合
 */
public class StringToDateConverter implements Converter<String, Date> {
    @Nullable
    @Override
    public Date convert(String json) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return simpleDateFormat.parse(json);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
 
    }
}
2.2 String类型转换为List集合类型

与2.1转换Date类型相似 这里使用了jackson框架进行转换

/**
 * 将String 转换为list集合
 */
public class StringToListConverter  implements Converter<String, List<OrderDetail>> {
 
    @Override
    public List<OrderDetail> convert(String json) {
        List<OrderDetail> priceDetails = JsonUtil.str2List(json,OrderDetail.class);
        return  priceDetails;
    }
 
}
2.3 转换类完成后,还需要将其交由Spring的容器进行处理,这里提供了两种方式

1、继承WebMvcConfigurationSupport类并将该对象创建进行添加

@Configuration
public class ApplicationConfig extends WebMvcConfigurationSupport {
    /**
     * 添加静态资源文件
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/img").addResourceLocations("/img/");
        registry.addResourceHandler("/static/css").addResourceLocations("/css/");
        registry.addResourceHandler("/static/js").addResourceLocations("/js/");
        registry.addResourceHandler("/static/swf").addResourceLocations("/swf/");
        registry.addResourceHandler("/static/media").addResourceLocations("/media/");
    }
 
    /**
     * 添加自定义的Converters和Formatters.
     */
    @Override
    protected void addFormatters(FormatterRegistry registry) {
        //添加字符串转换list的自定义转换器
        registry.addConverter(new StringToListConverter());
        //添加字符串转换Date的自定义转换器
        registry.addConverter(new StringToDateConverter());
    }
 
}

使用该方式会破坏SpringBoot默认加载静态文件的默认配置,需要重新进行添加,切记

2、第二种方式

@Configuration
public class SpringDataConvert {
 
    @Autowired
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
 
    /**
     * 增加字符串转换为List集合
     */
    @PostConstruct
    public void addConversionConfig() {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) requestMappingHandlerAdapter.getWebBindingInitializer();
        if (initializer.getConversionService() != null) {
            GenericConversionService genericConversionService = (GenericConversionService)initializer.getConversionService();
            //添加字符串转换为list集合的转换机器
            genericConversionService.addConverter(new StringToListConverter());
            //添加字符串转换为日期类型的字符串
            genericConversionService.addConverter(new StringToDateConverter());
 
        }
    }
}

三、注解方式

@JsonFormat与@DateTimeFormat注解的使用

背景:从数据库获取时间传到前端进行展示的时候,我们有时候可能无法得到一个满意的时间格式的时间日期,在数据库中显示的是正确的时间格式,获取出来却变成了很丑的时间戳,@JsonFormat注解很好的解决了这个问题,我们通过使用@JsonFormat可以很好的解决:后台到前台时间格式保持一致的问题,其次,另一个问题是,我们在使用WEB服务的时,可能会需要用到,传入时间给后台,比如注册新用户需要填入出生日期等,这个时候前台传递给后台的时间格式同样是不一致的,而我们的与之对应的便有了另一个注解,@DataTimeFormat便很好的解决了这个问题,接下来记录一下具体的@JsonFormat与DateTimeFormat的使用过程。

声明:关于@JsonFormat的使用,一定要导入正确完整的包。

1.注解@JsonFormat

注解@JsonFormat主要是后台到前台的时间格式的转换

1.使用maven引入@JsonFormat所需要的jar包,我贴一下我这里的pom文件的依赖

<!--JsonFormat-->
  
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.8</version>
        </dependency>
  
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.8</version>
        </dependency>
  
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>

2.在你需要查询出来的时间的数据库字段对应的实体类的属性上添加@JsonFormat

import java.util.Date;
  
import com.fasterxml.jackson.annotation.JsonFormat;
  
public class TestClass {
  
    //设置时区为上海时区,时间格式自己据需求定。
    @JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
    private Date testTime;
  
     
    public Date gettestTime() {
        return testTime;
    }
  
    public void settestTime(Date testTimee) {
        this.testTime= testTime;
    }
}

这里解释一下:

@JsonFormat(pattern=“yyyy-MM-dd”,timezone = “GMT+8”)

pattern:是你需要转换的时间日期的格式

timezone:是时间设置为东八区,避免时间在转换中有误差

提示:@JsonFormat注解可以在属性的上方,同样可以在属性对应的get方法上,两种方式没有区别

3.完成上面两步之后,我们用对应的实体类来接收数据库查询出来的结果时就完成了时间格式的转换,再返回给前端时就是一个符合我们设置的时间格式了

2.注解@DateTimeFormat

注解@DataFormAT主要是前后到后台的时间格式的转换

1.@DateTimeFormat的使用和@jsonFormat差不多,首先需要引入是spring还有jodatime,spring我就不贴了

<!-- joda-time -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.3</version>
        </dependency>

2.在controller层我们使用spring mvc 表单自动封装映射对象时,我们在对应的接收前台数据的对象的属性上加@@DateTimeFormat

@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date symstarttime;
 
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date symendtime;

我这里就只贴这两个属性了,这里我两个注解都同时使用了,因为我既需要取数据到前台,也需要前台数据传到后台,都需要进行时间格式的转换,可以同时使用

3.通过上面两个步骤之后,我们就可以获取一个符合自定义格式的时间格式存储到数据库了

3、总结:

注解@JsonFormat主要是后台到前台的时间格式的转换

注解@DataFormAT主要是前后到后台的时间格式的转换

时间格式化是使用频率非常高的,如何让时间格式化变得既简单又不用重复造轮子,那么就应将它抽象出来,作为全局的日期格式化处理,下面就结合实践简单介绍下几种优化方案

4、测试

@GetMapping("/timeTest")
  public OrderInfo timeTest() {
    OrderInfo order = new OrderInfo();
    order.setCreateTime(LocalDateTime.now());
    order.setUpdateTime(new Date());
    return order;
  }

1、@JsonFormat注解

使用@JsonFormat注解格式化时间,应该算是一个基本操作了,大部分开发者都应用此种方式,简单方便。

/**
 * @Author: xiaofu
 * @Description:
 */
public class OrderInfo {
 
  @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
  private LocalDateTime createTime;
 
  @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
  private Date updateTime;
 
  public LocalDateTime getCreateTime() {
    return createTime;
  }
 
  public void setCreateTime(LocalDateTime createTime) {
    this.createTime = createTime;
  }
 
  public Date getUpdateTime() {
    return updateTime;
  }
 
  public void setUpdateTime(Date updateTime) {
    this.updateTime = updateTime;
  }
}

测试一下结果,发现 Date 类型和 LocalDateTime 类型都格式化成功,但还是有个问题,这样做仍然比较繁琐,每个实体类的日期字段都要加@JsonFormat注解,重复的工作量也不小。接着往下看

2020052610530499.png

2、全局配置 (1)

Springboot 已经为我们提供了日期格式化 ${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss},这里我们需要进行全局配置,配置比较简单,也无需在实体类属性上添加@JsonFormat注解

public class OrderInfo {
 
  //@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
  private LocalDateTime createTime;
 
  //@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
  private Date updateTime;
 
  public LocalDateTime getCreateTime() {
    return createTime;
  }
 
  public void setCreateTime(LocalDateTime createTime) {
    this.createTime = createTime;
  }
 
  public Date getUpdateTime() {
    return updateTime;
  }
 
  public void setUpdateTime(Date updateTime) {
    this.updateTime = updateTime;
  }
}

只需要用@Configuration定义一个配置类,注入两个Bean即可完成全局日期格式化处理,这种方式也是当前我项目中正在用的方式

@Configuration
public class LocalDateTimeSerializerConfig {
 
  @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
  private String pattern;
 
  @Bean
  public LocalDateTimeSerializer localDateTimeDeserializer() {
    return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
  }
 
  @Bean
  public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
  }
}

这种方式可支持 Date 类型和 LocalDateTime 类型并存,那么有一个问题就是现在全局时间格式是yyyy-MM-dd HH:mm:ss,但有的字段却需要yyyy-MM-dd格式咋整?

那就需要配合@JsonFormat注解使用,在特定的字段属性添加@JsonFormat注解即可,因为@JsonFormat注解优先级比较高,会以@JsonFormat注解标注的时间格式为主

四、SpringBoot完整成功测试

1、3种Springboot全局时间格式化方式,提高开发效率利器

时间格式化在项目中使用频率是非常高的,当我们的 API 接口返回结果,需要对其中某一个 date 字段属性进行特殊的格式化处理,通常会用到 SimpleDateFormat 工具处理。

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date stationTime = dateFormat.parse(dateFormat.format(PayEndTime()));

可一旦处理的地方较多,不仅 CV 操作频繁,还产生很多重复臃肿的代码,而此时如果能将时间格式统一配置,就可以省下更多时间专注于业务开发了。

可能很多人觉得统一格式化时间很简单啊,像下边这样配置一下就行了,但事实上这种方式只对 date 类型生效。

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

而很多项目中用到的时间和日期API 比较混乱, java.util.Date 、 java.util.Calendar 和 java.time LocalDateTime 都存在,所以全局时间格式化必须要同时兼容性新旧 API。


看看配置全局时间格式化前,接口返回时间字段的格式。

@Data
public class OrderDTO {

    private LocalDateTime createTime;

    private Date updateTime;
}

很明显不符合页面上的显示要求(有人抬杠为啥不让前端解析时间,我只能说睡服代码比说服人容易得多~

3种Springboot全局时间格式化方式,提高开发效率利器

未做任何配置的结果

2、@JsonFormat 注解

@JsonFormat 注解方式严格意义上不能叫全局时间格式化,应该叫部分格式化,因为@JsonFormat 注解需要用在实体类的时间字段上,而只有使用相应的实体类,对应的字段才能进行格式化。

@Data
public class OrderDTO {

    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
    private LocalDateTime createTime;

    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime;
}

字段加上 @JsonFormat 注解后,LocalDateTime 和 Date 时间格式化成功。

3种Springboot全局时间格式化方式,提高开发效率利器

@JsonFormat 注解格式化

3、@JsonComponent 注解(推荐)

这是我个人比较推荐的一种方式,前边看到使用 @JsonFormat 注解并不能完全做到全局时间格式化,所以接下来我们使用 @JsonComponent 注解自定义一个全局格式化类,分别对 Date 和 LocalDate 类型做格式化处理。

@JsonComponent
public class DateFormatConfig {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    /**
     * @author xiaofu
     * @description date 类型全局时间格式化
     * @date 2020/8/31 18:22
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {

        return builder -> {
            TimeZone tz = TimeZone.getTimeZone("UTC");
            DateFormat df = new SimpleDateFormat(pattern);
            df.setTimeZone(tz);
            builder.failOnEmptyBeans(false)
                    .failOnUnknownProperties(false)
                    .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                    .dateFormat(df);
        };
    }

    /**
     * @author xiaofu
     * @description LocalDate 类型全局时间格式化
     * @date 2020/8/31 18:22
     */
    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }
}

看到 Date 和 LocalDate 两种时间类型格式化成功,此种方式有效。

3种Springboot全局时间格式化方式,提高开发效率利器

@JsonComponent 注解处理格式化

但还有个问题,实际开发中如果我有个字段不想用全局格式化设置的时间样式,想自定义格式怎么办?

那就需要和 @JsonFormat 注解配合使用了。

@Data
public class OrderDTO {

    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
    private LocalDateTime createTime;

    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
    private Date updateTime;
}

从结果上我们看到 @JsonFormat 注解的优先级比较高,会以 @JsonFormat 注解的时间格式为主。

3种Springboot全局时间格式化方式,提高开发效率利器

4、@Configuration 注解

这种全局配置的实现方式与上边的效果是一样的。

注意:在使用此种配置后,字段手动配置@JsonFormat 注解将不再生效。

@Configuration
public class DateFormatConfig2 {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    public static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Bean
    @Primary
    public ObjectMapper serializingObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }

    /**
     * @author xiaofu
     * @description Date 时间类型装换
     * @date 2020/9/1 17:25
     */
    @Component
    public class DateSerializer extends JsonSerializer<Date> {
        @Override
        public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException {
            String formattedDate = dateFormat.format(date);
            gen.writeString(formattedDate);
        }
    }

    /**
     * @author xiaofu
     * @description Date 时间类型装换
     * @date 2020/9/1 17:25
     */
    @Component
    public class DateDeserializer extends JsonDeserializer<Date> {

        @Override
        public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            try {
                return dateFormat.parse(jsonParser.getValueAsString());
            } catch (ParseException e) {
                throw new RuntimeException("Could not parse date", e);
            }
        }
    }

    /**
     * @author xiaofu
     * @description LocalDate 时间类型装换
     * @date 2020/9/1 17:25
     */
    public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(value.format(DateTimeFormatter.ofPattern(pattern)));
        }
    }

    /**
     * @author xiaofu
     * @description LocalDate 时间类型装换
     * @date 2020/9/1 17:25
     */
    public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException {
            return LocalDateTime.parse(p.getValueAsString(), DateTimeFormatter.ofPattern(pattern));
        }
    }
}

3种Springboot全局时间格式化方式,提高开发效率利器

五、joda-time

1、类总览

  • LocalDate - 没有时间的日期
  • LocalTime - 没有日期的时间
  • Instant - 时间线上的瞬时点
  • DateTime - 带时区的完整日期和时间
  • DateTimeZone - 一个更好的时区
  • Duration - 时间量
    Interval - 两个瞬间之间的时间

2、配置

使用maven导包

注意:jdk版本问题,这里选用依赖jdk1.5的版本,即2.3版,jdk1.8选用更高版本吧,因为jdk1.8的java.time 里面的api估摸着够用了。

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.4</version>
</dependency>

3、简单使用

  • joda 转 str
@Test
public void testJodaToStr(){
    DateTime dateTime = new DateTime();
    String string = dateTime.toString(TIME_PATTERN);
    String string2 = dateTime.toString(TIME_PATTERN,Locale.CHINA);
    System.out.println(string+string2);
}
  • str 转换为joda
 @Test
    public void testStrToJodaDate(){
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(DATETIME_PATTERN);

        DateTime parse = DateTime.parse("2018-12-11 17:06:30", dateTimeFormatter);

        System.out.println(parse);
    }
  • date 转 joda
 /**
     * date 转 joda
     */
    @Test
    public void testDateToJodaDate(){
        Date date = new Date();
    
        DateTime dateTime = new DateTime(date);
        System.out.println(date);
        System.out.println(dateTime);
    
    }
  • 日期比较
  DateTime d1 = new DateTime("2015-10-01"); 
  DateTime d2 = new DateTime("2016-02-01"); 
   
  //和系统时间比  
  boolean b1 = d1.isAfterNow();  
  boolean b2 = d1.isBeforeNow();  
  boolean b3 = d1.isEqualNow();  
   
  //和其他日期比  
  boolean f1 = d1.isAfter(d2);  
  boolean f2 = d1.isBefore(d2);  
  boolean f3 = d1.isEqual(d2);  
  • 计算间隔和区间
DateTime begin = new DateTime("2015-02-01");  
DateTime end = new DateTime("2016-05-01");  
 
//计算区间毫秒数  
Duration d = new Duration(begin, end);  
long millis = d.getMillis();  
 
//计算区间天数  
Period p = new Period(begin, end, PeriodType.days());  
int days = p.getDays();  
 
//计算特定日期是否在该区间内  
Interval interval = new Interval(begin, end);  
boolean contained = interval.contains(new DateTime("2015-03-01"));
  • 获取对应星期
 /**
         * 根据日期获取周几数据
         * @param dateTime
         * @return
         */
        private String getDayOfWeek(DateTime dateTime) {
            String dayOfWeek = "";
            switch (dateTime.getDayOfWeek()) {
                case DateTimeConstants.SUNDAY:
                    dayOfWeek = "周日";
                    break;
                case DateTimeConstants.MONDAY:
                    dayOfWeek = "周一";
                    break;
                case DateTimeConstants.TUESDAY:
                    dayOfWeek = "周二";
                    break;
                case DateTimeConstants.WEDNESDAY:
                    dayOfWeek = "周三";
                    break;
                case DateTimeConstants.THURSDAY:
                    dayOfWeek = "周四";
                    break;
                case DateTimeConstants.FRIDAY:
                    dayOfWeek = "周五";
                    break;
                case DateTimeConstants.SATURDAY:
                    dayOfWeek = "周六";
                default:
                    break;
            }
            return dayOfWeek;
        }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
# Geek-Framework 微服务快速开发脚手架 ### 平台简介 Geek-Framework是基于多个优秀的开源项目,高度整合封装而成的高效,高性能,强安全性的**开源**Java微服务快速开发框架。 Geek-Framework是在SpringBoot基础上搭建的一个Java基础开发框架,以Spring MVC为模型视图控制器,MyBatis为数据访问层, Apache Shiro和Spring-Security为权限授权层,redis进行缓存。 Geek-Framework主要定位于微应用的开发,已内置后台系统的基础功能,用户管理、角色管理、权限管理、会员管理、日志管理等;前台已经实现用户登录,注册等基础功能。 同时前后台会员实现分表管理,可扩展多角色系统、多权限系统。 采用分层设计、双重验证、提交数据安全编码、密码加密、访问验证、数据权限验证。 使用Maven做项目管理,提高项目的易开发性、扩展性。 --- ###更新日期2019-01-16 * 升级springboot版本为2.1.2.RELEASE application.yml增加以下配置,兼容最新的springboot版本 > spring:main:allow-bean-definition-overriding: true * 移除j2cache支持,移除原因为简化新手用户部署系统配置 * 更改后台登录为单realm,不再支持多realm * 优化日期时间工具类,使用Instant、LocalDateTime、LocalDate实现线性安全 * 修复Java开发规约中级警告及部分低级警告 * 增加debug日志输出开关 ###更新日期2018-12-28 * 项目增加健康检查暴露配置 * 根据JAVA开发手册对项目部分不符合开发手册的代码进行了修正,已修复高级警告、中级警告,由于低级警告较多,尚未修复,后续将持续修复 * 给前期已经使用项目的同学,可以使用【阿里巴巴Java开发规约插件p3c】进行修正,造成不便深表歉意 ###更新日期2018-10-08 * 最近学习了远程过程调用协议RPC(Remote Procedure Call Protocol),将本框架与dubbo做了一个集成,详见dubbo分支, * 为了方便大学家习dubbo的运行机制,本框架将dubbo的provider和customer作了一个整合,将官方demo里的方多应用整合成了一个,即在同一应用内启动消费端和服务端 * 注:如有实际业务需要请将服务端与消费端分离,此处整合仅供学习dubbo的运行机制和思想 ###更新日期2018-09-19 * 升级mybatis包为mybatis-spring-boot-starter,移除原有mybatis包 * 升级mapper包为mapper-spring-boot-starter * 升级pagehelper包为pagehelper-spring-boot-starter增加pagehelper-spring-boot-autoconfigure包 * 更改mybatis、mapper和pagehelper为自动配置,配置方式详见application.yml * 移除MyBatisConfig.java和MybatisMapperScannerConfig.java文件 * 更改升级pagehelper之后对排序方式的处理方式 * 增加事务测试样例,详见AdminController的save方法,此坑很深,爬了一天,由于没有对spring事务的深入了解,导致事务一直不成功,原因在于spring事务只能处理没有被捕获的异常信息,如果对方法增加了事务,请尽量避免用catch来获取异常,或进在cache里面增加抛出异常功能,使事务能够访问到 ###更新日期2018-09-19 * 升级J2cache为2.7.0版本,主要修复channel获取次数过多导致的错误问题,另个j2cache后期可能会移除对jedis的支持,所以还是提前升级了吧 * 调整二级缓存redis为lettuce,lettuce为spring推荐的redis操作方式,另个 ## 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。
这个资源是一个基于Spring Boot和MySQL的图书管理系统的完整源码,它使用了Java语言进行开发。该系统采用了MVC架构,将业务逻辑、数据访问和用户界面分离,使得代码结构清晰,易于维护和扩展。 在技术方面,该系统主要使用了以下技术: Spring Boot:这是一个用于快速构建Spring应用程序的框架,它可以自动配置项目,简化了项目的搭建和开发过程。 MySQL:这是一个关系型数据库管理系统,用于存储和管理图书信息。 JPA(Java Persistence API):这是一个用于操作数据库的Java API,它可以将Java对象映射到数据库表,简化了数据访问层的开发。 Thymeleaf:这是一个用于构建Web页面的模板引擎,它可以与Spring Boot无缝集成,简化了前端页面的开发。 Maven:这是一个用于管理项目依赖和构建的工具,它可以自动下载和管理项目所需的库和插件。 在功能方面,该图书管理系统主要包括以下功能: 图书信息管理:包括添加、删除、修改和查询图书信息,可以对图书的名称、作者、出版社、出版日期等信息进行管理。 读者信息管理:包括添加、删除、修改和查询读者信息,可以对读者的姓名、性别、联系方式等信息进行管理。 借阅管理:包括借阅图书、归还图书和查询借阅记录,可以对读者的借阅行为进行跟踪和管理。 统计报表:包括图书借阅排行榜、读者借阅排行榜等报表,可以对图书和读者的借阅情况进行统计分析。 总之,这个图书管理系统的完整源码提供了一个基于Spring Boot和MySQL的简单易用的图书管理解决方案,可以帮助开发者快速搭建一个功能完善的图书管理系统。
Spring5 是一个重要的版本,距离SpringFramework4差不多四年。在此期间,大多数增强都是在 SpringBoot 项目中完成的。在本文中,我们将很快了解到Spring5发行版中的一些令人兴奋的特性。 1. 基准升级 要构建和运行 Spring5 应用程序,你至少需要 J2EE7 和 JDK8。以前的 JDK 和 JavaEE 版本不再支持。 JavaEE7 包含: Servlet 3.1 JMS 2.0 JPA 2.1 JAX-RS 2.0 Bean Validation 1.1 与 Java 基准类似,许多其他框架的基准也有变化。例如: Hibernate 5 Jackson 2.6 EhCache 2.10 JUnit 5 Tiles 3 另外,请记下各种服务器最低支持版本。 Tomcat 8.5+ Jetty 9.4+ WildFly 10+ Netty 4.1+ Undertow 1.4+ 2. 兼容 JDK9 运行时 Spring5 发行版与 JDK9 发行日期非常接近。目标是让 Spring Framework5 在 JDK9 的 GA 之后正确运行。 Spring5 版本的候选版本已经在 classpath 和 modulepath 上支持 Java9 了。 GA版本中你可以期待良好的 JDK9 支持。 3. 使用 JDK8 特性 获取免费Spring 5 新特性视频详解可以群:554355695 在 Spring4.3 之前,JDK基准版本是6。所以 Spring4 必须支持 Java6,7 和8,为了保持向后兼容性, Spring 框架没有适应 Java8 带来的许多新特性,比如 lambda 表达式。 Spring5 的基准版本为8,因此它使用了 Java8 和9的许多新特性。例如: Spring 接口中的默认方法 基于 Java8 反射增强的内部代码改进 在框架代码中使用函数式编程 - lambda表达式 和 stream流 4. 响应式编程支持 响应式编程是 SpringFramework5.0 最重要的特性之一。响应式编程提供了另一种编程风格,专注于构建对事件做出响应的应用程序。 SpringFramework5 包含响应流(定义响应性API的语言中立尝试)和 Reactor(由Spring Pivotal团队提供的 Reactive Stream 的Java实现), 以用于其自身的用途以及其许多核心API。 Spring Web Reactive 在 spring-webmvc 模块中现有的(而且很流行)Spring Web MVC旁边的新的 spring-web-reactive 模块中。 请注意,在 Spring5 中,传统的 SpringMVC 支持 Servlet3.1 上运行,或者支持 JavaEE7 的服务器。 5. 函数式web框架 除了响应式功能之外,Spring5 还提供了一个函数式Web框架。它提供了使用函数式编程风格来定义端点的特性。 该框架引入了两个基本组件:HandlerFunction 和 RouterFunction。 HandlerFunction 表示处理接收到的请求并生成响应的函数。 RouterFunction 替代了 @RequestMapping 注解。它用于将接收到的请求路由到处理函数。例如: RouterFunction route = route(GET("/hello-world"), request -> Response.ok().body(fromObject("Hello World"))); 6. Kotlin支持 Kotlin 是一种静态类型的JVM语言,它让代码具有表现力,简洁性和可读性。 Spring5.0 对 Kotlin 有很好的支持。 7. 移除的特性 随着 Java、JavaEE 和其他一些框架基准版本的增加,SpringFramework5 取消了对几个框架的支持。例如: Portlet Velocity JasperReports XMLBeans JDO Guava

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值