How to Convert Date to Int? [closed]

喜你入骨 提交于 2019-12-13 23:20:32

问题


I'm Trying to get the current day value (example. 12) the assign it to a variable (example. today= 12).

        DateFormat DateFormat= new SimpleDateFormat ("dd");

        //get current day time with Date()
        Date day= new Date ();

        int day1 = Integer.valueOf(day);

Or

        DateFormat DateFormat= new SimpleDateFormat ("dd");

        //get current day time with Date()
        Date day= new Date ();

        int day1 = day;

回答1:


String year1= String.valueOf (year);
String month1= String.valueOf(month);
String day1= String.valueOf(day);

must be changed to

String year1= String.valueOf (num1);
String month1= String.valueOf(num2);
String day1= String.valueOf(num3);

because these 3 variables only hold the values entered by the user.

Also, not sure why you need the hour, because you never get that as inout from the user. In your case, what you've done for all these is use the new Date() as such which is throwing the exception.

The max you can do with your hour field is this

String hour1 = DateFormat3.format(hour); // Use the current time's hour value as you don't get any from user.

Side Note:- You can use a single SimpleDateFormat, single Scanner, and a lot of other optimizations, but that comes later, after you fix your code and logic.




回答2:


One thing which is obviously wrong is the way you use DateFormat. Its purpose is to format an instant in time as a date/time, so just one DateFormat is enough to render the full date, for example as YYYY/MM/DD.

Instead of asking the user for three separate entries, ask him to enter the full date in some format and define an appropriate DateFormat object to parse it into an instant. Here you're basically reimplementing that by hand.



来源:https://stackoverflow.com/questions/19334194/how-to-convert-date-to-int

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