spring-boot前端参数单位转换

 

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

public class OldFormat {
    public static void main(String[] args) throws ParseException {
        String dateString = "Thu Sep 07 2017 00:00:00 GMT+0800 (中国标准时间) 00:00:00";
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);
        Date dd = sdf.parse(dateString); //将字符串改为date的格式
        String resDate= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(dd);
        System.out.println(resDate);
    }
}

 

 

JAVA将字符串Sat Nov 25 2017 00:00:00 GMT+0800 (中国标准时间)转成标准时间

使用Spring MVC后台,需要接收前端传来的一个时间,时间格式如下:

Sat Nov 25 2017 00:00:00 GMT+0800 (中国标准时间)
刚开始使用如下的方式进行接收,发现无法接收到数据

@RequestMapping(value = "/queryResearchIndexByMemberIdAndLogDate",method = RequestMethod.GET)
public void queryByLogDate(Long memberId, Date logDate, HttpServletResponse response){
}


然后就想着,以字符串的方式进行接收,再将字符串转成Date格式。

@RequestMapping(value = "/queryResearchIndexByMemberIdAndLogDate",method = RequestMethod.GET)
public void queryByLogDate(Long memberId, String logDate, HttpServletResponse response){
}

SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss z", Locale.US);
try{
Date logDate1 = sdf.parse(logDate);
}catch(Exception e){
System.out.println(e.getMessage());
}
---------------------
作者:lym152898
来源:CSDN
原文:https://blog.csdn.net/lym152898/article/details/78789874
版权声明:本文为博主原创文章,转载请附上博文链接!

 

 

【Spring学习笔记-MVC-8.1】SpringMVC之类型转换@initBinder

1. 摘要


类型转换器常用于转换double、float、date等类型。

上文讲解了Converter类型转换器,这属于Spring 3新支持的类型转换器;
本文主要介绍@InitBinder,可参考如下链接:

功能说明:
当表单提交double、date等类型时,我们需要将其转换为java可识别的date,double等,如在浏览器中输入:
需要将其转化到Person对象中,此时需要对double类型进行转换。

2. 定义转换器类



  1. package com.ll.model;
  2. import java.beans.PropertyEditorSupport;
  3. public class PersonEditor extends PropertyEditorSupport {
  4. @Override
  5. public void setAsText(String text) throws IllegalArgumentException {
  6. Person p = new Person();
  7. if (text != null) {
  8. String[] items = text.split(":");
  9. p.setUsername(items[0]+"by propertyeEditor");
  10. p.setPasswd(items[1]);
  11. p.setRealName(items[2]);
  12. p.setPrice(Double.parseDouble(items[3]));
  13. }
  14. setValue(p);
  15. }
  16. @Override
  17. public String getAsText() {
  18. return getValue().toString();
  19. }
  20. }
 

3. 注册自定义编辑器


 

4. 类型转换测试



在浏览器中输入:
类型转换器会自动将"person=zhangsan:666:ssss:3.1415"转换为Person对象;

https://www.cnblogs.com/ssslinppp/p/4599436.html

【Spring学习笔记-MVC-9】SpringMVC数据格式化之日期转换@DateTimeFormat

1. 摘要


本文主要讲解Spring mvc数据格式化的具体步骤;
并讲解前台日期格式如何转换为java对象;

在之前的文章《【Spring学习笔记-MVC-8】SpringMVC之类型转换Converter》(对应链接: http://www.cnblogs.com/ssslinppp/p/4598102.html ) 中讲解了Spring MVC的类型转换,在此回顾下。

数据格式化,从本质上讲属于数据转换的范畴。Spring就是基于数据转换框架植入“格式化”功能的。
在数据转换时我们进行了如下配置:
我们使用的是ConversionServiceFactoryBean,而进行数据格式化时,只是将ConversionServiceFactoryBean改为FormattingConversionServiceFactoryBean即可,其他没有变化,如下是数据格式化的配置:

关于FormattingConversionServiceFactoryBean与ConversionServiceFactoryBean的比较:
  • ConversionService:只有数据转换功能;
  • ConversionServiceFactoryBean:与ConversionService对应;

  • FormattingConversionService:具有数据转换和数据格式化功能;
  • FormattingConversionServiceFactoryBean:与FormattingConversionService对应;可以注册自定义的转换器,又可以注册自定义的注解驱动器逻辑。

<mvc:annotation-driven/>标签内部默认创建的conversionService实例就是一个FormattingConversionServiceFactoryBean;
装配完FormattingConversionServiceFactoryBean后,Spring MVC对处理方法的入参绑定就支持注解驱动的功能了。
 

2. 具体实现


步骤1:配置FormattingConversionServiceFactoryBean

  1. <mvc:annotation-driven conversion-service="conversionService"/>
  2. <bean id="conversionService"
  3. class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
  4. <property name="converters">
  5. <list>
  6. <!-- <bean class="com.ll.model.StringToPersonConverter" /> -->
  7. </list>
  8. </property>
  9. </bean>

步骤2:使用@DateTimeFormat和@NumberFormat注解对象属性


步骤3:控制层


步骤4:前台请求

 

3. 简单介绍@DateTimeFormat与@NumberFormat


 https://www.cnblogs.com/ssslinppp/p/4600043.html

HowTo: Bind an input field to a Date property using Spring's SimpleFormController

If you're using the Spring SimpleFormController for binding your Java bean object to the UI, you may come across the case where you want to create a binding between an input field (where the user inputs a date) and your bean's Date property:

<form:input path="expiryDate" size="15" />


You will notice that you cannot just do it as normal, but to let your SimpleFormController accept the binding, you have to override the following method:

@Override
protected void initBinder(PortletRequest request, PortletRequestDataBinder binder) throws Exception {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(df, true));

super.initBinder(request,binder);
}

https://juristr.com/blog/2009/04/howto-bind-input-field-to-date-property/

Update: Using DateTimeFormat, introduced in java 8:

The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.

Your input format looks quite standard, except the trailing Z. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'". The trailing 'Z' is the interesting part. Usually there's time zone data here, like -0700. So the pattern would be ...Z, i.e. without apostrophes.

The output format is way more simple: "dd-MM-yyyy". Mind the small y -s.

Here is the example code:

DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018

Original answer - with old API SimpleDateFormat

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018

https://stackoverflow.com/questions/49752149/how-do-i-convert-2018-04-10t040000-000z-string-to-datetime

As per DateTimeFormat.ISO.DATE_TIME

The most common ISO DateTime Format yyyy-MM-dd'T'HH:mm:ss.SSSZ, e.g. 2000-10-31 01:30:00.000-05:00.

Where a Z represents a timezone value for example -05:00.

Your string value which is unparseable is 2015-09-26T01:30:00.000Z where Z must be replaced with actual timezone value.

For example 2015-09-26T01:30:00.000-04:00 will be parsed by ISO.DATE_TIME correctly
https://stackoverflow.com/questions/37110016/datetimeformat-with-iso-parameter-not-parsing-timezone-correctly

springmvc接收date类型参数:利用spring的DateTimeFormat注解

 

springmvc在表单提交接收date类型参数的时候会报错:Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'actionDate'

首先说下spring的版本,我用的spring 3.2.16.RELEASE。之前用的版本是3.0.5.RELEASE,按照下面的方法修改,还是一直报错误。

让springmvc提交表单时正确的接收date类型参数,主要分以下3个步骤:

1、在需要由string转Date的字段上加上DateTimeFormat注解,代码如下

@DateTimeFormat(pattern="yyyy-MM-dd")
private Date actionDate;

2、添加joda-time的jar包

如果用的是maven,请在pom.xml中添加如下代码:

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

3、在springmvc配置文件中添加注解映射的支持,代码如下:

<mvc:annotation-driven />

通过以上3个步骤就可以让springmvc在提交表单时接收date类型的字段了。这种方法也是我认为的最好的方法。

http://www.codingwhy.com/view/763.html

springmvc接收date类型参数:在controller中使用initBinder注解

前面的文章我们讲了通过DateTimeFormat注解让springmvc接收date参数,这篇文章,我们讲解下在controller中使用initBinder注解解决springmvc表单提交接收date参数的方法,利用initBinder注解的方式我个人认为不是太好,因为在实际开发中,我的日期字段,可能需要保存的格式不同,一个是yyyy-MM-dd,另一个是yyyy-MM-dd HH:mm:ss。这样的情况,initBinder注解就不适用了。

利用initBinder注解解决表单接收date类型参数的代码如下,在controller方法里面,重写initBinder方法即可,具体代码如下:

@InitBinder
protected void initBinder(WebDataBinder binder) {
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd",2);
	binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true),2);
}

通过以上代码就解决Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'actionDate'这样的错误了。
http://www.codingwhy.com/view/764.html

@DateTimeFormat 注解可对

java.util.Date、java.util.Calendar、java.long.Long 时间类型进行标注:

– pattern 属性:类型为字符串。指定解析/格式化字段数据的模式,
如:”yyyy-MM-dd hh:mm:ss”

– iso 属性:类型为 DateTimeFormat.ISO。指定解析/格式化字段数据
的ISO模式,包括四种:ISO.NONE(不使用) -- 默
认、ISO.DATE(yyyy-MM-dd) 、ISO.TIME(hh:mm:ss.SSSZ)、
ISO.DATE_TIME(yyyy-MM-dd hh:mm:ss.SSSZ)

– style 属性:字符串类型。通过样式指定日期时间的格式,由两位字
符组成,第一位表示日期的格式,第二位表示时间的格式:S:短日
期/时间格式、M:中日期/时间格式、L:长日期/时间格式、F:完整
日期/时间格式、-:忽略日期或时间格式

@DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birth;


作者:二月长河
链接:https://www.jianshu.com/p/b64cfe960038
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

java解析形如yyyy-MM-dd'T'HH:mm:ss.SSS'Z'的时间格式

发生这一错误的主要原因是Controller类中需要接收的是Date类型,但是在页面端传过来的是String类型,最终导致了这个错误。

这里提供两种解决方案,一种是局部转换,一种是全局转换。

<form action="login.do" method="post">
<input type="text" name="birthday" value="2017-07-12 22:04:00">
<input type="submit" value="提交">
</form>


一.局部转换
@Controller
public class UserController{

@RequestMapping(value="/login.do")
public String login(String username,Date birthday){
System.out.println("________");
return "";
}

//只需要加上下面这段即可,注意不能忘记注解
@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request) {

//转换日期
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
}
}
---------------------
作者:东天里的冬天
来源:CSDN
原文:https://blog.csdn.net/gwd1154978352/article/details/75041733
版权声明:本文为博主原创文章,转载请附上博文链接!






 

前端时间单位用的是unix时间戳,单位秒,而java后端用的是Date类型。
在request请求时,如何把前端的时间戳类型优雅的转换为后端的Date类型呢。

如果你想在response时,把后端的Date类型转换到前端的时间戳类型
可以看这篇文章java中JsonSerializer用法,前后端单位转换必备

这里我使用的是SpringBoot框架。

Controller代码

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result add(@Valid OrderForm form,
                      BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
        
        }

OrderForm对象

@Data
public class OrderForm {

    private String id;

    private String userName;
    
    private Date addTime;
}

这时,如果直接传addTime=1488264066是会报错的,提示类型不正确。
但如果你把addTime类型改成Long就可以

@Data
public class OrderForm {

    private String id;

    private String userName;
    
    private Long addTime;
}

说明spring已经帮我们做了String到Long的转换,但是没有做转换到Date类型。
我们来扩展即可。

在src/java/下建一个名字为bind的包。
下面放这3个java文件

/**
* 扩展类型转换
*/
public class CustomDateEditor extends PropertyEditorSupport {

    /**
     * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        setValue(new Date(Long.decode(text)));
    }

    /**
     * @see java.beans.PropertyEditorSupport#getAsText()
     */
    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        return (value != null ? String.valueOf(TimeUnit.MILLISECONDS.toSeconds(value.getTime())) : "");
    }

}
/**
* 扩展web初始化的配置
*/
public class CustomDateWebBindingInitializer implements WebBindingInitializer {

    /**
     * @see org.springframework.web.bind.support.WebBindingInitializer#initBinder(org.springframework.web.bind.WebDataBinder,
     *      org.springframework.web.context.request.WebRequest)
     */
    @Override
    public void initBinder(WebDataBinder binder, WebRequest request) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor());
    }

}
/**
* 让配置在request请求时生效
*/
@Configuration
public class CustomDateEditorConfiguration {

    @Autowired
    public void setWebBindingInitializer(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
        requestMappingHandlerAdapter.setWebBindingInitializer(new CustomDateWebBindingInitializer());
    }
}

配置好后,就可以接收到Date类型的内容了,全局生效。


作者:nul1
链接:https://www.jianshu.com/p/3a5fc2564501
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。


Java中

    //-----------------------------------------------------------------------
    /**
     * The ISO date-time formatter that formats or parses a date-time with an
     * offset, such as '2011-12-03T10:15:30+01:00'.
     * <p>
     * This returns an immutable formatter capable of formatting and parsing
     * the ISO-8601 extended offset date-time format.
     * The format consists of:
     * <ul>
     * <li>The {@link #ISO_LOCAL_DATE_TIME}
     * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
     *  they will be handled even though this is not part of the ISO-8601 standard.
     *  Parsing is case insensitive.
     * </ul>
     * <p>
     * The returned formatter has a chronology of ISO set to ensure dates in
     * other calendar systems are correctly converted.
     * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
     */
    public static final DateTimeFormatter ISO_OFFSET_DATE_TIME;
    static {
        ISO_OFFSET_DATE_TIME = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .append(ISO_LOCAL_DATE_TIME)
                .appendOffsetId()
                .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
    }



    //-----------------------------------------------------------------------
    /**
     * The ISO date-time formatter that formats or parses a date-time with an
     * offset, such as '2011-12-03T10:15:30+01:00'.
     * <p>
     * This returns an immutable formatter capable of formatting and parsing
     * the ISO-8601 extended offset date-time format.
     * The format consists of:
     * <ul>
     * <li>The {@link #ISO_LOCAL_DATE_TIME}
     * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then
     *  they will be handled even though this is not part of the ISO-8601 standard.
     *  Parsing is case insensitive.
     * </ul>
     * <p>
     * The returned formatter has a chronology of ISO set to ensure dates in
     * other calendar systems are correctly converted.
     * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style.
     */
    public static final DateTimeFormatter ISO_OFFSET_DATE_TIME;
    static {
        ISO_OFFSET_DATE_TIME = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .append(ISO_LOCAL_DATE_TIME)
                .appendOffsetId()
                .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
    }

 

    //-----------------------------------------------------------------------
    /**
     * The ISO instant formatter that formats or parses an instant in UTC,
     * such as '2011-12-03T10:15:30Z'.
     * <p>
     * This returns an immutable formatter capable of formatting and parsing
     * the ISO-8601 instant format.
     * When formatting, the second-of-minute is always output.
     * The nano-of-second outputs zero, three, six or nine digits digits as necessary.
     * When parsing, time to at least the seconds field is required.
     * Fractional seconds from zero to nine are parsed.
     * The localized decimal style is not used.
     * <p>
     * This is a special case formatter intended to allow a human readable form
     * of an {@link java.time.Instant}. The {@code Instant} class is designed to
     * only represent a point in time and internally stores a value in nanoseconds
     * from a fixed epoch of 1970-01-01Z. As such, an {@code Instant} cannot be
     * formatted as a date or time without providing some form of time-zone.
     * This formatter allows the {@code Instant} to be formatted, by providing
     * a suitable conversion using {@code ZoneOffset.UTC}.
     * <p>
     * The format consists of:
     * <ul>
     * <li>The {@link #ISO_OFFSET_DATE_TIME} where the instant is converted from
     *  {@link ChronoField#INSTANT_SECONDS} and {@link ChronoField#NANO_OF_SECOND}
     *  using the {@code UTC} offset. Parsing is case insensitive.
     * </ul>
     * <p>
     * The returned formatter has no override chronology or zone.
     * It uses the {@link ResolverStyle#STRICT STRICT} resolver style.
     */
    public static final DateTimeFormatter ISO_INSTANT;
    static {
        ISO_INSTANT = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendInstant()
                .toFormatter(ResolverStyle.STRICT, null);
    }

java.time.format.DateTimeFormatter#ISO_INSTANT

 

 

Customizing Formats


Version note: This Date and Time section uses the date and time APIs in the java.util package. The java.time APIs, available in the JDK 8 release, provides a comprehensive date and time model that offers significant improvements over the java.util classes. The java.time APIs are described in the Date Time trail. The Legacy Date-Time Code page might be of particular interest.

The previous section, Using Predefined Formats, described the formatting styles provided by the DateFormat class. In most cases these predefined formats are adequate. However, if you want to create your own customized formats, you can use the SimpleDateFormat class.

The code examples that follow demonstrate the methods of the SimpleDateFormat class. You can find the full source code for the examples in the file named SimpleDateFormatDemo.

About Patterns

When you create a SimpleDateFormat object, you specify a pattern String. The contents of the pattern String determine the format of the date and time. For a full description of the pattern's syntax, see the tables in Date Format Pattern Syntax.

The following code formats a date and time according to the pattern String passed to the SimpleDateFormat constructor. The String returned by the format method contains the formatted date and time that are to be displayed.

Date today;
String output;
SimpleDateFormat formatter;

formatter = new SimpleDateFormat(pattern, currentLocale);
today = new Date();
output = formatter.format(today);
System.out.println(pattern + " " + output);

The following table shows the output generated by the previous code example when the U.S. Locale is specified:

Customized Date and Time Formats
PatternOutput
dd.MM.yy 30.06.09
yyyy.MM.dd G 'at' hh:mm:ss z 2009.06.30 AD at 08:29:36 PDT
EEE, MMM d, ''yy Tue, Jun 30, '09
h:mm a 8:29 PM
H:mm 8:29
H:mm:ss:SSS 8:28:36:249
K:mm a,z 8:29 AM,PDT
yyyy.MMMMM.dd GGG hh:mm aaa 2009.June.30 AD 08:29 AM

Patterns and Locale

The SimpleDateFormat class is locale-sensitive. If you instantiate SimpleDateFormat without a Locale parameter, it will format the date and time according to the default Locale. Both the pattern and the Locale determine the format. For the same pattern, SimpleDateFormat may format a date and time differently if the Locale varies.

In the example code that follows, the pattern is hardcoded in the statement that creates the SimpleDateFormat object:

Date today;
String result;
SimpleDateFormat formatter;

formatter = new SimpleDateFormat("EEE d MMM yy", currentLocale);
today = new Date();
result = formatter.format(today);
System.out.println("Locale: " + currentLocale.toString());
System.out.println("Result: " + result);

When the currentLocale is set to different values, the preceding code example generates this output:

Locale: fr_FR
Result: mar. 30 juin 09
Locale: de_DE
Result: Di 30 Jun 09
Locale: en_US
Result: Tue 30 Jun 09

Date Format Pattern Syntax

You can design your own format patterns for dates and times from the list of symbols in the following table:

SymbolMeaningPresentationExample
G era designator Text AD
y year Number 2009
M month in year Text & Number July & 07
d day in month Number 10
h hour in am/pm (1-12) Number 12
H hour in day (0-23) Number 0
m minute in hour Number 30
s second in minute Number 55
S millisecond Number 978
E day in week Text Tuesday
D day in year Number 189
F day of week in month Number 2 (2nd Wed in July)
w week in year Number 27
W week in month Number 2
a am/pm marker Text PM
k hour in day (1-24) Number 24
K hour in am/pm (0-11) Number 0
z time zone Text Pacific Standard Time
' escape for text Delimiter (none)
' single quote Literal '

Characters that are not letters are treated as quoted text. That is, they will appear in the formatted text even if they are not enclosed within single quotes.

The number of symbol letters you specify also determines the format. For example, if the "zz" pattern results in "PDT," then the "zzzz" pattern generates "Pacific Daylight Time." The following table summarizes these rules:

PresentationNumber of SymbolsResult
Text 1 - 3 abbreviated form, if one exists
Text >= 4 full form
Number minimum number of digits is required shorter numbers are padded with zeros (for a year, if the count of 'y' is 2, then the year is truncated to 2 digits)
Text & Number 1 - 2 number form
Text & Number 3 text form





 

posted @ 2018-12-28 19:44  沧海一滴  阅读(1702)  评论(0编辑  收藏  举报