这里面我们简单的学习一下springboot中关于数据格式化的使用。我以为你不是个好人,没想到你连个坏人都不是。

 

我们的测试环境是springboot,一个将字符串格式化成时间的例子。代码结构如下:

springboot---->springboot中的格式化(一)

一、定义我们的字符串格式化器

package com.linux.huhx.learn.format;

import org.springframework.format.Formatter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @Author: huhx
 * @Date: 2017-12-15 下午 4:16
 * @Desc: formatter的学习
 */
@Component
public class DateFormatter implements Formatter<Date> {
    private SimpleDateFormat dateFormat;

    @Override
    public Date parse(String text, Locale locale) throws ParseException {
        System.out.println("parse input text: " + text);
        System.out.println("parse date: " + dateFormat.parse(text));
        return dateFormat.parse(text);
    }

    public DateFormatter() {
        dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        dateFormat.setLenient(false);
    }

    @Override
    public String print(Date object, Locale locale) {
        System.out.println("print method." + object);
        return dateFormat.format(object);
    }
}

 

 二、我们的测试控制器类

package com.linux.huhx.learn.format;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @Author: huhx
 * @Date: 2017-12-15 下午 4:24
 */

@RestController
@RequestMapping("/formatter")
public class DateFormatterAction {

    @PostMapping("/date")
    public Date formatterStringToDate(Date date) {
        System.out.println("action method: " + date.toString());
        return date;
    }
}

使用postman发送post请求:http://localhost:9998/formatter/date。

springboot---->springboot中的格式化(一)

返回的数据:以下的时间戳是spring经过转换生成的

1513311132000

控制台打印数据:

parse input text: 20171215121212
parse date: Fri Dec 15 12:12:12 CST 2017
action method: Fri Dec 15 12:12:12 CST 2017

 

友情链接

 

相关文章:

  • 2022-01-08
  • 2022-12-23
  • 2021-10-08
  • 2022-12-23
  • 2022-02-06
  • 2021-12-22
  • 2021-05-21
  • 2021-11-08
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-24
相关资源
相似解决方案