Java 如何将日期转换为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19334194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Convert Date to Int?
提问by Liwa'a M Awar
I'm Trying to get the current day value (example. 12) the assign it to a variable (example. today= 12).
我正在尝试获取当前日期值(示例。12)并将其分配给一个变量(示例。今天= 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;
采纳答案by SudoRahul
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.
因为这 3 个变量只保存用户输入的值。
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.
另外,不确定为什么需要hour
,因为您永远不会从用户那里获得 inout 。在您的情况下,您为所有这些所做的事情是使用new Date()
抛出异常的本身。
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.
旁注:-您可以使用单个 SimpleDateFormat、单个 Scanner 和许多其他优化,但在您修复代码和逻辑之后会出现。
回答by Marko Topolnik
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.
明显错误的一件事是您使用DateFormat
. 它的目的是将一个瞬间格式化为日期/时间,所以只要一个DateFormat
就足以呈现完整的日期,例如 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.
与其要求用户输入三个单独的条目,不如让他以某种格式输入完整日期并定义适当的DateFormat
对象以将其解析为瞬间。在这里,您基本上是手动重新实现它。