如何在java中使用值创建日期对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22326339/
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 create Date Object with values in java
提问by Banukobhan Nagendram
I need a date object for date 2014-02-11. I can't directly create it like this,
我需要一个日期为 2014-02-11 的日期对象。我不能像这样直接创建它,
Date myDate = new Date(2014, 02, 11);
So I'm doing like follows,
所以我正在做如下,
Calendar myCalendar = new GregorianCalendar(2014, 2, 11);
Date myDate = myCalendar.getTime();
Is there any easy way to create date object in java?
有没有什么简单的方法可以在java中创建日期对象?
回答by edubriguenti
I think the best way would be using a SimpleDateFormat
object.
我认为最好的方法是使用SimpleDateFormat
对象。
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = "2014-02-11";
Date dateObject = sdf.parse(dateString); // Handle the ParseException here
回答by Selva
Try this
尝试这个
Calendar cal = Calendar.getInstance();
Date todayDate = new Date();
cal.setTime(todayDate);
// Set time fields to zero
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
todayDate = cal.getTime();
回答by Adrian Shum
Gotcha: passing 2 as month may give you unexpected result: in Calendar API, month is zero-based. 2 actually means March.
陷阱:将 2 作为月份传递可能会给您带来意想不到的结果:在 Calendar API 中,月份是从零开始的。2实际上是指三月。
I don't know what is an "easy" way that you are looking for as I feel that using Calendar is already easy enough.
我不知道您正在寻找什么“简单”的方式,因为我觉得使用 Calendar 已经足够简单了。
Remember to use correct constants for month:
请记住为月份使用正确的常量:
Date date = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();
Another way is to make use of DateFormat, which I usually have a util like this:
另一种方法是使用 DateFormat,我通常有一个像这样的工具:
public static Date parseDate(String date) {
try {
return new SimpleDateFormat("yyyy-MM-dd").parse(date);
} catch (ParseException e) {
return null;
}
}
so that I can simply write
这样我就可以简单地写
Date myDate = parseDate("2014-02-14");
Yet another alternative I prefer: Don't use Java Date/Calendar anymore. Switch to JODA Time or Java Time (aka JSR310, available in JDK 8+). You can use LocalDate
to represent a date, which can be easily created by
我更喜欢的另一种选择:不再使用 Java 日期/日历。切换到 JODA Time 或 Java Time(又名 JSR310,在 JDK 8+ 中可用)。您可以使用LocalDate
来表示日期,它可以通过以下方式轻松创建
LocalDate myDate =LocalDate.parse("2014-02-14");
// or
LocalDate myDate2 = new LocalDate(2014, 2, 14);
// or, in JDK 8+ Time
LocalDate myDate3 = LocalDate.of(2014, 2, 14);
回答by Basil Bourque
tl;dr
tl;博士
LocalDate.of( 2014 , 2 , 11 )
If you insist on using the terrible old java.util.Date
class, convert from the modern java.timeclasses.
如果您坚持使用糟糕的旧java.util.Date
类,请从现代java.time类转换。
java.util.Date // Terrible old legacy class, avoid using. Represents a moment in UTC.
.from( // New conversion method added to old classes for converting between legacy classes and modern classes.
LocalDate // Represents a date-only value, without time-of-day and without time zone.
.of( 2014 , 2 , 11 ) // Specify year-month-day. Notice sane counting, unlike legacy classes: 2014 means year 2014, 1-12 for Jan-Dec.
.atStartOfDay( // Let java.time determine first moment of the day. May *not* start at 00:00:00 because of anomalies such as Daylight Saving Time (DST).
ZoneId.of( "Africa/Tunis" ) // Specify time zone as `Continent/Region`, never the 3-4 letter pseudo-zones like `PST`, `EST`, or `IST`.
) // Returns a `ZonedDateTime`.
.toInstant() // Adjust from zone to UTC. Returns a `Instant` object, always in UTC by definition.
) // Returns a legacy `java.util.Date` object. Beware of possible data-loss as any microseconds or nanoseconds in the `Instant` are truncated to milliseconds in this `Date` object.
Details
细节
If you want "easy", you should be using the new java.time packagein Java 8 rather than the notoriously troublesome java.util.Date & .Calendar classes bundled with Java.
如果您想要“简单”,您应该使用Java 8 中的新java.time 包,而不是与 Java 捆绑在一起的臭名昭著的 java.util.Date 和 .Calendar 类。
java.time
时间
The java.timeframework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes.
Java 8 及更高版本中内置的java.time框架取代了麻烦的旧 java.util.Date/.Calendar 类。
Date-only
仅限日期
A LocalDate
class is offered by java.time to represent a date-only value without any time-of-day or time zone. You do need a time zone to determine a date, as a new day dawns earlier in Paris than in Montréal for example. The ZoneId
class is for time zones.
LocalDate
java.time 提供了一个类来表示没有任何时间或时区的仅日期值。您确实需要一个时区来确定日期,例如,巴黎比蒙特利尔更早迎来新的一天。该ZoneId
课程适用于时区。
ZoneId zoneId = ZoneId.of( "Asia/Singapore" );
LocalDate today = LocalDate.now( zoneId );
Dump to console:
转储到控制台:
System.out.println ( "today: " + today + " in zone: " + zoneId );
today: 2015-11-26 in zone: Asia/Singapore
今天:2015-11-26 在区域:亚洲/新加坡
Or use a factory method to specify the year, month, day.
或者使用工厂方法指定年、月、日。
LocalDate localDate = LocalDate.of( 2014 , Month.FEBRUARY , 11 );
localDate: 2014-02-11
本地日期:2014-02-11
Or pass a month number 1-12 rather than a DayOfWeek
enum object.
或者传递月份数字 1-12 而不是DayOfWeek
枚举对象。
LocalDate localDate = LocalDate.of( 2014 , 2 , 11 );
Time zone
时区
A LocalDate
has no real meaning until you adjust it into a time zone. In java.time, we apply a time zone to generate a ZonedDateTime
object. That also means a time-of-day, but what time? Usually makes sense to go with first moment of the day. You might think that means the time 00:00:00.000
, but not always true because of Daylight Saving Time (DST) and perhaps other anomalies. Instead of assuming that time, we ask java.time to determine the first moment of the day by calling atStartOfDay
.
在LocalDate
您将其调整到时区之前,A没有实际意义。在 java.time 中,我们应用一个时区来生成一个ZonedDateTime
对象。这也意味着一天中的时间,但什么时间?通常与一天中的第一刻一起使用是有意义的。您可能认为这意味着 time 00:00:00.000
,但由于夏令时 (DST) 和可能的其他异常情况,这并不总是正确的。我们不是假设那个时间,而是通过调用 java.time 来确定一天中的第一个时刻atStartOfDay
。
Specify a proper time zone namein the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are nottrue time zones, not standardized, and not even unique(!).
以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/region
America/Montreal
Africa/Casablanca
Pacific/Auckland
EST
IST
ZoneId zoneId = ZoneId.of( "Asia/Singapore" );
ZonedDateTime zdt = localDate.atStartOfDay( zoneId );
zdt: 2014-02-11T00:00+08:00[Asia/Singapore]
zdt: 2014-02-11T00:00+08:00[亚洲/新加坡]
UTC
世界标准时间
For back-end work (business logic, database, data storage & exchange) we usually use UTCtime zone. In java.time, the Instant
class represents a moment on the timeline in UTC. An Instant object can be extracted from a ZonedDateTime by calling toInstant
.
对于后端工作(业务逻辑、数据库、数据存储和交换),我们通常使用UTC时区。在java.time 中,Instant
该类表示UTC 时间线上的一个时刻。可以通过调用从 ZonedDateTime 中提取 Instant 对象toInstant
。
Instant instant = zdt.toInstant();
instant: 2014-02-10T16:00:00Z
即时:2014-02-10T16:00:00Z
Convert
转变
You should avoid using java.util.Date
class entirely. But if you must interoperate with old code not yet updated for java.time, you can convert back-and-forth. Look to new conversion methods added to the old classes.
您应该java.util.Date
完全避免使用类。但是,如果您必须与尚未为java.time更新的旧代码进行互操作,则可以来回转换。查看添加到旧类的新转换方法。
java.util.Date d = java.util.from( instant ) ;
…and…
…和…
Instant instant = d.toInstant() ;
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
- Much of the java.time functionality 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功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 更高版本的 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
,和更多。
UPDATE: The Joda-Timelibrary is now in maintenance mode, and advises migration to the java.timeclasses. I am leaving this section in place for history.
更新:Joda-Time库现在处于维护模式,并建议迁移到java.time类。我将把这一部分留在历史上。
Joda-Time
乔达时间
For one thing, Joda-Time uses sensible numbering so February is 2
not 1
. Another thing, a Joda-Time DateTime truly knows its assigned time zone unlike a java.util.Date which seems to have time zone but does not.
一方面,Joda-Time 使用合理的编号,所以二月2
不是1
。另一件事,Joda-Time DateTime 真正知道其分配的时区,不像 java.util.Date 似乎有时区但没有。
And don't forget the time zone. Otherwise you'll be getting the JVM's default.
并且不要忘记时区。否则,您将获得 JVM 的默认值。
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Singapore" );
DateTime dateTimeSingapore = new DateTime( 2014, 2, 11, 0, 0, timeZone );
DateTime dateTimeUtc = dateTimeSingapore.withZone( DateTimeZone.UTC );
java.util.Locale locale = new java.util.Locale( "ms", "SG" ); // Language: Bahasa Melayu (?). Country: Singapore.
String output = DateTimeFormat.forStyle( "FF" ).withLocale( locale ).print( dateTimeSingapore );
Dump to console…
转储到控制台...
System.out.println( "dateTimeSingapore: " + dateTimeSingapore );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "output: " + output );
When run…
运行时…
dateTimeSingapore: 2014-02-11T00:00:00.000+08:00
dateTimeUtc: 2014-02-10T16:00:00.000Z
output: Selasa, 2014 Februari 11 00:00:00 SGT
Conversion
转换
If you need to convert to a java.util.Date for use with other classes…
如果您需要转换为 java.util.Date 以与其他类一起使用...
java.util.Date date = dateTimeSingapore.toDate();
回答by Paykoman
I think your date comes from php and is written to html (dom) or? I have a php-function to prep all dates and timestamps. This return a formation that is be needed.
我认为您的日期来自 php 并写入 html (dom) 或?我有一个 php 函数来准备所有日期和时间戳。这返回了一个需要的阵型。
$timeForJS = timeop($datetimeFromDatabase['payedon'], 'js', 'local'); // save 10/12/2016 09:20 on var
this format can be used on js to create new Date...
这种格式可以在js上使用来创建新的日期...
<html>
<span id="test" data-date="<?php echo $timeForJS; ?>"></span>
<script>var myDate = new Date( $('#test').attr('data-date') );</script>
</html>
What i will say is, make your a own function to wrap, that make your life easyr. You can us my func as sample but is included in my cms you can not 1 to 1 copy and paste :)
我要说的是,让你自己的函数来包装,让你的生活更轻松。您可以使用我的 func 作为示例,但包含在我的 cms 中,您不能 1 对 1 复制和粘贴:)
function timeop($utcTime, $for, $tz_output = 'system')
{
// echo "<br>Current time ( UTC ): ".$wwm->timeop('now', 'db', 'system');
// echo "<br>Current time (USER): ".$wwm->timeop('now', 'db', 'local');
// echo "<br>Current time (USER): ".$wwm->timeop('now', 'D d M Y H:i:s', 'local');
// echo "<br>Current time with user lang (USER): ".$wwm->timeop('now', 'datetimes', 'local');
// echo '<br><br>Calculator test is users timezone difference != 0! Tested with "2014-06-27 07:46:09"<br>';
// echo "<br>Old time (USER -> UTC): ".$wwm->timeop('2014-06-27 07:46:09', 'db', 'system');
// echo "<br>Old time (UTC -> USER): ".$wwm->timeop('2014-06-27 07:46:09', 'db', 'local');
/** -- */
// echo '<br><br>a Time from db if same with user time?<br>';
// echo "<br>db-time (2019-06-27 07:46:09) time left = ".$wwm->timeleft('2019-06-27 07:46:09', 'max');
// echo "<br>db-time (2014-06-27 07:46:09) time left = ".$wwm->timeleft('2014-06-27 07:46:09', 'max', 'txt');
/** -- */
// echo '<br><br>Calculator test with other formats<br>';
// echo "<br>2014/06/27 07:46:09: ".$wwm->ntimeop('2014/06/27 07:46:09', 'db', 'system');
switch($tz_output){
case 'system':
$tz = 'UTC';
break;
case 'local':
$tz = $_SESSION['wwm']['sett']['tz'];
break;
default:
$tz = $tz_output;
break;
}
$date = new DateTime($utcTime, new DateTimeZone($tz));
if( $tz != 'UTC' ) // Only time converted into different time zone
{
// now check at first the difference in seconds
$offset = $this->tz_offset($tz);
if( $offset != 0 ){
$calc = ( $offset >= 0 ) ? 'add' : 'sub';
// $calc = ( ($_SESSION['wwm']['sett']['tzdiff'] >= 0 AND $tz_output == 'user') OR ($_SESSION['wwm']['sett']['tzdiff'] <= 0 AND $tz_output == 'local') ) ? 'sub' : 'add';
$offset = ['math' => $calc, 'diff' => abs($offset)];
$date->$offset['math']( new DateInterval('PT'.$offset['diff'].'S') ); // php >= 5.3 use add() or sub()
}
}
// create a individual output
switch( $for ){
case 'js':
$format = 'm/d/Y H:i'; // Timepicker use only this format m/d/Y H:i without seconds // Sett automatical seconds default to 00
break;
case 'js:s':
$format = 'm/d/Y H:i:s'; // Timepicker use only this format m/d/Y H:i:s with Seconds
break;
case 'db':
$format = 'Y-m-d H:i:s'; // Database use only this format Y-m-d H:i:s
break;
case 'date':
case 'datetime':
case 'datetimes':
$format = wwmSystem::$languages[$_SESSION['wwm']['sett']['isolang']][$for.'_format']; // language spezific output
break;
default:
$format = $for;
break;
}
$output = $date->format( $format );
/** Replacement
*
* D = day short name
* l = day long name
* F = month long name
* M = month short name
*/
$output = str_replace([
$date->format('D'),
$date->format('l'),
$date->format('F'),
$date->format('M')
],[
$this->trans('date', $date->format('D')),
$this->trans('date', $date->format('l')),
$this->trans('date', $date->format('F')),
$this->trans('date', $date->format('M'))
], $output);
return $output; // $output->getTimestamp();
}
回答by Ankush
import java.io.*;
import java.util.*;
import java.util.HashMap;
public class Solution
{
public static void main(String[] args)
{
HashMap<Integer,String> hm = new HashMap<Integer,String>();
hm.put(1,"SUNDAY");
hm.put(2,"MONDAY");
hm.put(3,"TUESDAY");
hm.put(4,"WEDNESDAY");
hm.put(5,"THURSDAY");
hm.put(6,"FRIDAY");
hm.put(7,"SATURDAY");
Scanner in = new Scanner(System.in);
String month = in.next();
String day = in.next();
String year = in.next();
String format = year + "/" + month + "/" + day;
Date date = null;
try
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
date = formatter.parse(format);
}
catch(Exception e){
}
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println(hm.get(dayOfWeek));
}
}
回答by Tody.Lu
From Java8:
从 Java8:
import java.time.Instant;
import java.util.Date;
Date date = Date.from(Instant.parse("2000-01-01T00:00:00.000Z"))
回答by Syed Danish Haider
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
//format as u want
try {
String dateStart = "June 14 2018 16:02:37";
cal.setTime(sdf.parse(dateStart));
//all done
} catch (ParseException e) {
e.printStackTrace();
}
回答by Adam Silenko
Simplest ways:
最简单的方法:
Date date = Date.valueOf("2000-1-1");
LocalDate localdate = LocalDate.of(2000,1,1);
LocalDateTime localDateTime = LocalDateTime.of(2000,1,1,0,0);