How to set date format of a date into Date but not String?

北慕城南 提交于 2019-12-11 16:16:36

问题


Here's what I need to do :

I want to change the date2 into a Date but not String.

 Date date = new Date();
 DateFormat format = new SimpleDateFormat ("yyyy/MM/dd",Locale.ENGLISH);
 String date2 = format.format(date);

It does not allow me to save date2 as a Date. Someone please help me. Thanks


回答1:


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

String your_date = "2014-12-15 00:00:00.0";
DateFormat format = new SimpleDateFormat ("yyyy/MM/dd",Locale.ENGLISH);
Date new_date = format.parse(your_date);
System.out.println(new_date);



回答2:


java.util.Date objects do not have a format. They just represent a date value. You cannot "set the format of a Date object" because a Date object can't store this information.

What you are asking ("how do I set the format of a Date object") is not possible, because that's not how Date objects work.

What you should do instead is just work with the Date object and at the point where it needs to be displayed, you convert it to a String in the desired format using a SimpleDateFormat object.



来源:https://stackoverflow.com/questions/27482606/how-to-set-date-format-of-a-date-into-date-but-not-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!