多语言展示
当前在线:1644今日阅读:27今日分享:41

java 日期格式如何设置

java设置date的多种方式。
方法/步骤
1

我们在日常开发过程中经常使用yyyy-MM-dd的格式,如何设置:public static String dateToString(Date date) { if (date == null) { return ''; } SimpleDateFormat sdf = new SimpleDateFormat('yyyy-MM-dd'); String str = sdf.format(date); return str; }

2

返回yyyy-MM-dd的日期格式,不过是String类型的,这种形式的在json中会经常使用。

3

如何将日期转换为任意类型的,根据自己传的格式: public static String dateToString(Date date,String pattern) { if (date == null) { return ''; } try{ SimpleDateFormat sdf = new SimpleDateFormat(pattern); String str = sdf.format(date); return str;

4

}catch(Exception e){e.printStackTrace();return '';}}将日期转换为想要的格式,根据传入的参数不同转换不同的date类型。

5

我们通过表单提交时间格式的时候,如果希望时间自动转换为string类型的,可以使用spring mvc的表单类型转换:

6

@InitBinderpublic void initBinder(WebDataBinder binder){   DateFormat format = new SimpleDateFormat('yyyy-MM-dd');   binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));}在controller层添加对日期的转换,spring mvc会自动注册,在提交form数据的时候,自动对date进行转换。

7

设置当天0点0分0秒public static Date getTimesmorning() throws ParseException {        Calendar cal = Calendar.getInstance();        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);        Date beginOfDate = cal.getTime();        return beginOfDate;            }

推荐信息