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;
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值