Java 如何获取当前日期时间 – date() 和 calender()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38958719/
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 get current date time – date() and calender()
提问by Yavuz
I want hours and minutes will start from the current date will be October 10, 2016 end of days
我希望小时和分钟将从当前日期开始,将是 2016 年 10 月 10 日结束的日子
package com.mkyong.date;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDifferentExample
{
public static void main(String[] args)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/15/2012 10:31:48";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try
{
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Results :
结果 :
2016/08/15 18:54:03
2016/08/15 18:54:03
1097 Days1 Hours 1 Minute 50 Second
My want to result for example :
100 days 5 hours 2 minutes
回答by Sumit Gupta
public final void set(int year,int month,int date)- this method of Calendar class can be used to set date .
public final void set(int year,int month,int date)- Calendar 类的这个方法可用于设置日期。
public final void set(int year, int month,int date,int hourOfDay,int minute,int second)can be used to set time too.
public final void set(int year, int month,int date,int hourOfDay,int minute,int second)也可以用来设置时间。
Calendar.getInstance()by default set current date and time.`
Calendar.getInstance()默认设置当前日期和时间。`
回答by Basil Bourque
Avoid old date-time classes
避免旧的日期时间课程
You are using troublesome old legacy date-time classes bundled with the earliest versions of Java. Use java.time classes instead.
您正在使用与最早版本的 Java 捆绑在一起的麻烦的旧的遗留日期时间类。改用 java.time 类。
Parsing
解析
Your input strings are almost in standard ISO 8601 format. Replace the SPACE in the middle with a T
. The java.time classes parse/generate strings using ISO 8601 formats by default. So no need to specify a formatting pattern.
您的输入字符串几乎采用标准 ISO 8601 格式。将中间的 SPACE 替换为T
. java.time 类默认使用 ISO 8601 格式解析/生成字符串。所以不需要指定格式模式。
String startInput = "01/14/2012 09:29:58".replace( " " , "T" );
String stopInput = "01/15/2012 10:31:48".replace( " " , "T" );
LocalDateTime
LocalDateTime
Your inputs lack any information about offset-from-UTC or time zone. So we parse as LocalDateTime
objects.
您的输入缺少有关 UTC 偏移量或时区的任何信息。所以我们解析为LocalDateTime
对象。
LocalDateTime startLdt = LocalDateTime.parse( startInput );
LocalDateTime stopLdt = LocalDateTime.parse( stopInput );
If you work further with these types you will get results based on generic 24-hour days while ignoring anomalies such as Daylight Saving Time (DST).
如果您进一步使用这些类型,您将获得基于通用 24 小时制的结果,同时忽略夏令时 (DST) 等异常情况。
If you know the context of this data is a particular time zone, apply the zone to get ZonedDateTime
.
如果您知道此数据的上下文是特定时区,请应用该区域以获取ZonedDateTime
.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime start = startLdt.atZone( zoneId );
ZonedDateTime stop = stopLdt.atZone( zoneId );
If you want the current moment as the start or the stop, call now
. Pass the desired/expected time zone rather than relying on the JVM's current default time zone.
如果您想将当前时刻作为开始或停止,请调用now
。传递所需/预期的时区,而不是依赖 JVM 的当前默认时区。
ZonedDateTime now = ZonedDateTime.now( zoneId );
Duration
期间
The Duration
class represents a span of time as a total of seconds plus a fraction of a second in nanoseconds resolution.
所述Duration
类表示一时间跨度为总的秒数加在纳秒分辨率的几分之一秒。
Duration duration = Duration.between( start , stop );
Oddly, in Java 8 this class lacks methods to get the number of days, hours, etc. making up this span of time. Java 9 adds to…Part
methods.
奇怪的是,在 Java 8 中,这个类缺少获取构成这段时间的天数、小时数等的方法。Java 9添加了to…Part
方法。
long days = duration.toDaysPart();
int hours = duration.toHoursPart();
int minutes = duration.toMinutesPart();
Until Java 9 you can do the math yourself.
在 Java 9 之前,您可以自己进行数学计算。
About java.time
关于 java.time
The java.timeframework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了旧的麻烦的日期时间类,例如java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to java.time.
现在处于维护模式的Joda-Time项目建议迁移到 java.time。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backportand further adapted to Androidin ThreeTenABP.
多的java.time功能后移植到Java 6和7在ThreeTen-反向移植并且还适于的Android在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
,等。