springboot---->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。

返回的数据:以下的时间戳是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

 

友情链接

 

转载于:https://www.cnblogs.com/huhx/p/baseusespringbootformatter1.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值