日期构造函数java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20744474/
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
Date constructor java
提问by JmRag
Hello I am trying to get the current date at java at a Class I created but everything fails. I've seen in many sites
e.g. http://www.mkyong.com/java/java-date-and-calendar-examples/that the date constructor has no arguments
e.g. Date date = new Date();
您好,我正在尝试在我创建的类中获取 java 的当前日期,但一切都失败了。我在很多网站上看到过,例如http://www.mkyong.com/java/java-date-and-calendar-examples/日期构造函数没有参数,例如Date date = new Date();
Now in my project I try to use it like this and I get the error
现在在我的项目中,我尝试像这样使用它,但出现错误
that The constructor Date() is undefined
构造函数 Date() 未定义
How is this possible? I give you the full code so far
这怎么可能?到目前为止我给你完整的代码
import java.sql.Date;
import java.text.SimpleDateFormat;
public class Utility {
String title;
int ID;
Date date;
Utility(String t,int ID){
this.ID=ID+1;
title=t;
SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
Date a=new Date();// I get the error here
String date = sdf.format(a);
System.out.print(date);
}
}
I work at Eclipse IDE. Can you help me?
我在 Eclipse IDE 工作。你能帮助我吗?
采纳答案by Matteo
The examples you found are for java.util.Date
while you are using java.sql.Date
您找到的示例适用于java.util.Date
您使用时java.sql.Date
java.sql.Date
has two constructors
Date(long date)
: Constructs a Date object using the given milliseconds time value.Date(int year, int month, int day)
: which is deprecated
and no default
Date()
constructor.java.util.Date
among others has a default constructor without arguments
Date()
: Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
java.sql.Date
有两个构造函数
Date(long date)
: 使用给定的毫秒时间值构造一个 Date 对象。Date(int year, int month, int day)
: 已弃用
并且没有默认
Date()
构造函数。java.util.Date
其中有一个没有参数的默认构造函数
Date()
: 分配一个 Date 对象并初始化它,以便它表示它被分配的时间,测量到最接近的毫秒。
When importing classes, Eclipse will help you fining possible candidates but always check if the first suggestion is really what you want.
导入类时,Eclipse 将帮助您确定可能的候选者,但始终检查第一个建议是否真的是您想要的。
回答by Matthias
You are using the wrong Date
class.
您使用了错误的Date
类。
Have a look at your imports. Don't use java.sql.Date
use java.util.Date
instead.
看看你的进口。不要使用java.sql.Date
usejava.util.Date
代替。
回答by kdabir
You are importing java.sql.Date
use java.util.Date
您正在导入java.sql.Date
使用java.util.Date
回答by Sarath Kumar Sivan
You have imported wrong class. It is java.util.Date
and not java.sql.Date
您导入了错误的类。它是java.util.Date
和不是java.sql.Date
回答by Serdar
You can also use use java.util.Calendar as follows:
您还可以使用 java.util.Calendar 如下:
Calendar c = Calendar.getInstance();
java.util.Date date = c.getTime();
回答by Basil Bourque
tl;dr
tl;博士
Get today's date:
获取今天的日期:
LocalDate.now()
Generate text representing today's date, in your desired format:
以您想要的格式生成表示今天日期的文本:
LocalDate
.now()
.format(
DateTimeFormatter.ofPattern( "d/M/uuuu" )
)
23/1/2019
23/1/2019
Details
细节
The answer by Matteois correct. You are abusing the java.sql.Date class by treating it as java.util.Date.
Matteo的回答是正确的。您通过将 java.sql.Date 类视为 java.util.Date 来滥用它。
But the answers suggesting using java.util.Calendar questions are misguided. Both java.util.Date & Calendar are notoriously bad classes, with poor design and implementation. They are outmoded by the modern java.time.* JSR 310 classes.
但是建议使用 java.util.Calendar 问题的答案是错误的。java.util.Date 和 Calendar 都是出了名的糟糕的类,设计和实现都很糟糕。它们已被现代 java.time.* JSR 310 类过时。
Also, when working with date-time you should always think about time zone. Otherwise you'll be getting default time zone with possibly varying behavior at runtime.
此外,在使用日期时间时,您应该始终考虑时区。否则,您将获得默认时区,在运行时可能会有不同的行为。
java.time
时间
ZonedDateTime zonedDateTime = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
If you want a date-only value, without a time-of-day and without a time zone, use LocalDate
.
如果您想要一个仅限日期的值,没有时间和时区,请使用LocalDate
.
LocalDate
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zoneor offset-from-UTC.
该LocalDate
级表示没有时间的天,没有一个日期,只值时区或偏移从-UTC。
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.
时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any momentduring runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
如果未指定时区,JVM 会隐式应用其当前默认时区。该默认值可能会在运行时随时更改(!),因此您的结果可能会有所不同。最好将您想要/预期的时区明确指定为参数。
Specify a proper time zone namein the format of Continent/Region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 2-4 letter abbreviation such as EST
or IST
as they are nottrue time zones, not standardized, and not even unique(!).
以、、 或等格式指定正确的时区名称。永远不要使用 2-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。Continent/Region
America/Montreal
Africa/Casablanca
Pacific/Auckland
EST
IST
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM's current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
如果您想使用 JVM 的当前默认时区,请询问它并作为参数传递。如果省略,代码读起来会变得模棱两可,因为我们不确定您是否打算使用默认值,或者您是否像许多程序员一样没有意识到这个问题。
ZoneId z = ZoneId.systemDefault() ; // Get JVM's current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
或指定日期。您可以通过数字设置月份,对于 1 月至 12 月,合理编号为 1-12。
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month
enum objects pre-defined, one for each month of the year. Tip: Use these Month
objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year
& YearMonth
.
或者,更好的是使用Month
预定义的枚举对象,一年中的每个月都有一个。提示:Month
在整个代码库中使用这些对象而不仅仅是整数,以使您的代码更具自文档性、确保有效值并提供类型安全。同上Year
& YearMonth
。
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
About java.time
关于java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*
classes.
您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Most of the java.timefunctionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.timeclasses.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9、Java SE 10、Java SE 11及更高版本 - 标准 Java API 的一部分,具有捆绑实现。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 大部分java.time功能在ThreeTen-Backport中向后移植到 Java 6 & 7 。
- 安卓
- 更高版本的 Android 捆绑实现java.time类。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。