如何在java中初始化日期类型的变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34119441/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:20:53  来源:igfitidea点击:

How to initialize a variable of date type in java?

javadatevariables

提问by owlprogrammer

import java.util.Date;
Date firstDate; 

I don't know how to intialize the firstDate for example for String you say

我不知道如何初始化 firstDate 例如你说的 String

String line1="First line" 

but what is the format for date can you give me an example?

但是日期的格式是什么,你能给我举个例子吗?

回答by SMA

To initialize to current date, you could do something like:

要初始化为当前日期,您可以执行以下操作:

Date firstDate = new Date();

To get it from String, you could use SimpleDateFormatlike:

要从 String 获取它,您可以使用SimpleDateFormat ,例如:

String dateInString = "10-Jan-2016";
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
try {
    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));
} catch (ParseException e) {
    //handle exception if date is not in "dd-MMM-yyyy" format
}

回答by Ron

To parse a Date from a String you can choose which format you would like it to have. For example:

要从字符串解析日期,您可以选择您希望它具有的格式。例如:

public Date StringToDate(String s){

    Date result = null;
    try{
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        result  = dateFormat.parse(s);
    }

    catch(ParseException e){
        e.printStackTrace();

    }
    return result ;
}

If you would like to use this method now, you will have to use something like this

如果你现在想使用这个方法,你将不得不使用这样的东西

Date date = StringToDate("2015-12-06 17:03:00");

For more explanation you should check out http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

有关更多解释,您应该查看http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

回答by ThankThePhoenicians

Here's the Javadoc in Oracle's website for the Date class: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
If you scroll down to "Constructor Summary," you'll see the different options for how a Date object can be instantiated. Like all objects in Java, you create a new one with the following:

这是 Oracle 网站中 Date 类的 Javadoc:https: //docs.oracle.com/javase/8/docs/api/java/util/Date.html
如果向下滚动到“构造函数摘要”,您将看到如何实例化 Date 对象的不同选项。与 Java 中的所有对象一样,您可以使用以下内容创建一个新对象:

Date firstDate = new Date(ConstructorArgsHere);

Now you have a bit of a choice. If you don't pass in any arguments, and just do this,

现在你有一点选择。如果你不传递任何参数,就这样做,

Date firstDate = new Date();

it will represent the exact date and time at which you called it. Here are some other constructors you may want to make use of:

它将代表您调用它的确切日期和时间。以下是您可能想要使用的其他一些构造函数:

Date firstDate1 = new Date(int year, int month, int date);
Date firstDate2 = new Date(int year, int month, int date, int hrs, int min);
Date firstDate3 = new Date(int year, int month, int date, int hrs, int min, int sec);

回答by Basil Bourque

tl;dr

tl;博士

Use Instant, replacement for java.util.Date.

使用Instant,替代java.util.Date

Instant.now()  // Capture current moment as seen in UTC.

If you must have a Date, convert.

如果你必须有一个Date,转换。

java.util.Date.from( Instant.now() ) 

java.time

时间

The java.util.Date & .Calendar classes have been supplanted by the java.time framework built into Java 8 and later. The new classes are a tremendousimprovement, inspired by the successful Joda-Time library.

java.util.Date 和 .Calendar 类已被内置于 Java 8 及更高版本中的 java.time 框架所取代。受成功的 Joda-Time 库的启发,新类是一个巨大的改进。

The java.time classes tend to use static factory methodsrather than constructorsfor instantiating objects.

java.time 类倾向于使用静态工厂方法而不是构造函数来实例化对象。

To get the current moment in UTC time zone:

要获取 UTC 时区的当前时刻:

Instant instant = Instant.now();

To get the current moment in a particular time zone:

要获取特定时区的当前时刻:

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zoneId );

If you must have a java.util.Date for use with other classes not yet updated for the java.time types, convert from Instant.

如果您必须有一个 java.util.Date 与尚未针对 java.time 类型更新的其他类一起使用,请从Instant.

java.util.Date date = java.util.Date.from( zdt.toInstant() );

Table of date-time types in Java, both modern and legacy.

Java 中的日期时间类型表,包括现代的和传统的。



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

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

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

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 类?

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 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

回答by Scirocco

java.util.Dateconstructor with parameters like new Date(int year, int month, int date, int hrs, int min). is deprecated and preferably do not use it any more. Oracle docs prefers the way over java.util.Calendar. So you can set any date and instantiate Date object through the getTime() method.

java.util.Date构造函数,带有 new Date(int year, int month, int date, int hrs, int min) 等参数。已弃用,最好不要再使用它。Oracle 文档更喜欢java.util.Calendar的方式。所以你可以通过 getTime() 方法设置任何日期并实例化 Date 对象。

Calendar calendar = Calendar.getInstance();
calendar.set(2018, 11, 31, 59, 59, 59);
Date happyNewYearDate = calendar.getTime();

Notice that month number starts from 0

请注意,月份编号从 0 开始