In NetBeans, I run the code below.
The output from one run is
Intended time = 1970-0-1 0:0:0.000
GC time in ms = 102
Reformated GC time = 1970-01-01 00:00:00.102
Deprecated Date ms = 0
Deprecated time = 1970-01-01 00:00:00.000
The output from another run is
Intended time = 1970-0-1 0:0:0.000
GC time in ms = 575
Reformated GC time = 1970-01-01 00:00:00.575
Deprecated Date ms = 0
Deprecated time = 1970-01-01 00:00:00.000
Q1: Why is the Reformatted time (from GregorianCalendar set(...) method) have extra milliseconds - Deprecated - using new Date(...) does not!
Q2: Why does the number of ms vary from run to run?
public class TestGregorianCalendar {
public static void main(String[] args){
String timeZoneString = "GMT+00";
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone(timeZoneString));
int year = 1970;
int month = 0; // Jan
int day = 1;
int hour = 0;
int min = 0;
int sec = 0;
calendar.set(year, month, day, hour, min, sec);
long ms;
Date date;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
df.setTimeZone(TimeZone.getTimeZone(timeZoneString));
System.out.println("Intended time = "+year+"-"+month+"-"+day
+" "+hour+":"+min+":"+sec+".000");
calendar.set(year, month, day, hour, min, sec);
ms = calendar.getTimeInMillis();
System.out.println("GC time in ms = "+Long.toString(ms));
date = new Date(ms);
System.out.println("Reformated GC time = "+df.format(date));
Date deprecatedDate = new Date(year-1900, month, day, hour+1, min, sec);
System.out.println("Deprecated Date ms = "+Long.toString(deprecatedDate.getTime()));
System.out.println("Deprecated time = "+df.format(deprecatedDate));
}
}
Grateful for insight!
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work.
OffsetDateTime dateTime = OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
System.out.println(dateTime);
long ms = dateTime.toInstant().toEpochMilli();
System.out.println(ms);
Output:
1970-01-01T00:00Z
0
There are no extra milliseconds, or they would gave been printed twice, once in each of the output lines. java.time sanely numbers months the same way humans do, so I have given January as 1. The last 0 in the argument list to OffsetDateTIme.of() is nanosecond of second and ensures that the fraction of second will be 0.
If you want formatted output:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
System.out.println(dateTime.format(formatter));
1970-01-01 00:00:00.000
What went wrong in your code?
Mark Rotteveel already in the comment has answered both of your questions. new GregorianCalendar(TimeZone.getTimeZone(timeZoneString)) created a GregorianCalendar representing the current moment in the specified time zone, with millisecond precision. calendar.set(year, month, day, hour, min, sec) sets the mentioned fields to those values. It does not change other fields such as era and millisecond (of second). So the millisecond value that you get reflects the time of the second the GregorianCalendar object was created, which obviously is not the same each time. This explains the apparently random variations. This is just one of very many confusing sides of GregorianCalendar. I recommend that you don’t use that class.
new Date(year-1900, month, day, hour+1, min, sec) — whoa, using the constructor that has been deprecated since February 1997 because it works unreliably across time zones — creates a new Date object from those values alone without looking at the clock, so here the millisecond of second is 0.
Link
Oracle tutorial: Date Time explaining how to use java.time.
Instant.EPOCH
Instant.EPOCH is the constant for the 1970-01-01T00:00:00Z epoch instant.
import java.time.Instant;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.EPOCH;
System.out.println(instant);
}
}
Output:
1970-01-01T00:00:00Z
In case you need a date-time string representing the instant into a different pattern, you can convert it into OffsetDateTime using Instant#atOffset and then format the same using a DateTimeFormatter instantiated with the desired pattern.
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.EPOCH;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
String formatted = formatter.format(instant.atOffset(ZoneOffset.UTC));
System.out.println(formatted);
}
}
Output:
1970-01-01 00:00:00.000
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. I suggest you should stop using them completely and switch to the modern date-time API. Learn more about the modern date-time API at Trail: Date Time.
I have created a class with two fields that need to be dates, start_date and date_passed. I have been researching the best way in java to have dates in a YYYY MM DD format that allows for easy date subtraction, and the ability to "make-up" a date, say in the future for example.
Example of what I'd like it to do...
library.circulate_book("Chemistry", **start date here**) //actual date or random date
library.pass_book("Chemistry", **Date Passed here**) //random date such as 5 days after start date
int days_had = Date_Passed - start_date
So far, I've found plenty of ways to format dates using Calendars and Date classes, but have yet to find one that looks like it would work considering most dates end up as Strings. Any suggestions/small examples are greatly appreciated! Also, any links to examples would be awesome!
tl;dr
To move from one date to another by adding/subtracting a number of days.
LocalDate.now(
ZoneId.of( "Pacific/Auckland" )
)
.minusDays( 5 )
To calculate the number of days, months, and years elapsed between two dates.
ChronoUnit.DAYS.between( start , stop )
Parsing
First you must parse your string inputs into date-time objects. Then you work on preforming your business logic with those objects.
Stop thinking of date-time values as strings, that will drive you nuts. We work with date-time objects in our code; we exchange data with users or other apps using a String representation of that date-time object.
In Java 8 and later, use the java.time framework. See Tutorial.
You want only a date, without time-of-day, so we can use the LocalDate class.
That funky double-colon syntax is a method reference, a way to say what method should be called by other code.
String input = "2015 01 02";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "yyyy MM dd" );
LocalDate localDate = formatter.parse ( input , LocalDate :: from );
Current date
Determining today’s date requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate todayTunis = LocalDate.now( z ) ;
If you want the JVM’s current default time zone, call ZoneId.systemDefault.
Subtracting Dates
This has been addressed many times before on StackOveflow.com. For example, How to subtract X days from a date using Java calendar?. For details, see other Answers such as this one by me and this one by me for more details. Tip: "elapsed" is a key search word.
Use ChronoUnit.DAYS enum to calculate count of days elapsed.
LocalDate weekLater = localDate.plusDays ( 7 );
long daysElapsed = java.time.temporal.ChronoUnit.DAYS.between( todayTunis , weekLater ) ;
Dump to console.
System.out.println ( "localDate: " + localDate + " to " + weekLater + " in days: " + daysElapsed );
localDate: 2015-01-02 to 2015-01-09 in days: 7
The best way to do this in Java-8 is not the flawed answer of Basil Bourque but this approach:
String startDate = "2016 01 02";
String passedDate = "2016 02 29";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
LocalDate date1 = LocalDate.parse(startDate, formatter);
LocalDate date2 = LocalDate.parse(passedDate, formatter);
long elapsedDays = ChronoUnit.DAYS.between(date1, date2);
System.out.println(elapsedDays); // 58 (correct)
The suggested use of java.time.Period.getDays() is dangerous and often wrong as soon as the elapsed duration exceeds one month. The whole Period is P1M27D so this code effectively only queries the partial amount of elapsed days (there is also an elapsed month):
System.out.println(Period.between(date1, date2).getDays()); // 27 (WRONG!!!)
A satisfying solution using the classes java.util.Date, GregorianCalendar etc. is hard to find. You can use the answer of Tacktheritrix but have to be aware of the fact that the calculated count of elapsed days might differ due to the sub-day-parts of java.util.Date and is also not reliable because of ignoring day-light-saving switches (where the clock jumps by one hour in many parts of the world).
Side note: At least 8 external libraries offer good answers to your problem, too. But I think, your simple use-case does not justify the embedding of an extra library unless you are not yet on Java-8. Any alternative solution how to count the elapsed days between two dates would not be easier than in Java-8 - only similar. And since you accepted the Java-8-related answer of Basil Bourque, I assume that you are indeed on Java-8 so I leave out the answer how to solve your problem with other libraries.
Use the Java 8 Date API or Joda, no need for new inventions.
You can find some examples here: http://examples.javacodegeeks.com/core-java/java-8-datetime-api-tutorial/
Here's an answer using Calendar:
Calendar cal = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal2.setTime(cal.getTime());
cal2.add(Calendar.DAY_OF_YEAR, 5);
System.out.println((cal2.getTimeInMillis() - cal.getTimeInMillis()) / (1000d * 60 * 60 * 24));
LocalDate startDate = LocalDate.of(2009, 9, 1);
LocalDate today = LocalDate.now();
Period p = Period.between(startDate, today);
System.out.println("Years " + p.getYears());
System.out.println("Months " + p.getMonths());
System.out.println("Days " + p.getDays());
If you are stuck withan older java you can use SimpleDateFormat.
//For substraction
long differenceInMillis = date1.getTime() - date2.getTime();
//Date Format
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy MM dd");
String dateAsString = dateFormat.format(date1); //To get a text representation
Date dateParsed = dateFormat.parse(dateAsString); //To get it back as date
I need to compare the time a local file was downloaded with a time in the future/past to see if the file needs to be re-downloaded to update it. I can get the time the local file was last downloaded with :
long timeSinceCreateFile = myFile.lastModified();
What I need is to check timeSinceCreateFile with a time that is the NEXT Friday at 21:30hs and if the current time: System.currentTimeMillis()
is in the future to this then re-download the file.
I've read heaps on Calendar, Time, Date, Joda-Time etc. but have not been able to figure out how to get a moment in time as a specific Day, Hour, Minuet, etc. that is RELATIVE to timeSinceCreateFile
Edit
I need to know the time in milliseconds between when a file was downloaded (or last modified) long timeSinceCreateFile = myFile.lastModified(); and the FOLLOWING Friday at 21:30hs (as in the Friday at 21:30hrs AFTER timeSinceCreateFile)
I can then compare the "FOLLOWING FRIDAY AT 21:30hrs" milliseconds to the current time 'System.currentTimeMillis()` and if one is greater than the other re-download the file.
Hope this clarified my question, if not let me know because I really need help with this.
Thanks.
Your temporal condition "next Friday at 21:30" is hard to realize in standard Java-library using java.util.Calendar and java.util.Date.
In Joda-Time it also requires a non-trivial workaround (again with loop).
In Java-8 (new time library JSR-310 in package java.time) an acceptable solution using specialized methods in TemporalAdjusters is possible, but since you operate on Android, this is not the way to go.
Instead here an alternative solution in my library Time4J which does not need any error-prone loops or complex conditions:
import static net.time4j.PlainDate.DAY_OF_WEEK;
import static net.time4j.Weekday.FRIDAY;
File myFile = new File("");
long timeSinceCreateFile = myFile.lastModified();
// conversion to global timestamp in Time4J-format
Moment fileTSP = TemporalTypes.MILLIS_SINCE_UNIX.transform(timeSinceCreateFile);
// what ever you need (or just TZID timezone = Timezone.ofSystem().getID();)
TZID timezone = AMERICA.MONTREAL;
// "next friday" is a local time condition => convert to local timestamp
PlainTimestamp localTSP = fileTSP.toZonalTimestamp(timezone);
PlainTime walltime2130 = PlainTime.of(21, 30);
// move to next time 21:30 (possibly on next day) and then to next or same Friday
localTSP =
localTSP.with(PlainTime.COMPONENT.setToNext(walltime2130))
.with(DAY_OF_WEEK.setToNextOrSame(FRIDAY));
// convert current time to local timestamp and compare at 21:30
boolean downloadNeeded = SystemClock.inZonalView(timezone).now().isAfter(localTSP);
GregorianCalendar ? set the date to your year, month, day, 21:30, set day of week to friday. Use getTime to get a long millisecs. This will give you a UNIX time for some friday 21:30 close to your date. Keep adding or removing the number of milliseconds in a week until the time minus your file time is in the range [0 number of milliseconds in a week]. Warning with month, it's 0 based.
public static void main(String[] args){
long fileCreateTime = new Date().getTime();
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(new Date(fileCreateTime));
calendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
calendar.set(Calendar.HOUR_OF_DAY, 21);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long MILLISECS_IN_A_WEEK = 7*24*60*60*1000;
long calendarMillisecs = calendar.getTime().getTime();
while(calendarMillisecs<fileCreateTime){
calendarMillisecs += MILLISECS_IN_A_WEEK;
}
while(calendarMillisecs>fileCreateTime+MILLISECS_IN_A_WEEK){
calendarMillisecs -= MILLISECS_IN_A_WEEK;
}
System.out.println(new Date(calendarMillisecs));
}
Ugly, but will work.
Avoid java.util.Date & .Calendar
Avoid java.util.Date and .Calendar because they are notoriously troublesome, flawed, and confusing. Use either Joda-Time or the new java.time package in Java 8.
Joda-Time
In Joda-Time 2.4.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime start = DateTime.now( timeZone );
// DateTime start = new DateTime( fileLastModifiedMillis, timeZone );
DateTime dateTime = start;
while ( dateTime.getDayOfWeek() != DateTimeConstants.FRIDAY ) {
dateTime = dateTime.plusDays( 1 );
}
To compare…
boolean isLate = oneDateTime.isAfter( someOtherDateTime );
This question already has answers here:
How to get the current date and time
(10 answers)
Closed 2 years ago.
What's the best way to get the current date/time in Java?
It depends on what form of date / time you want:
If you want the date / time as a single numeric value, then System.currentTimeMillis() gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java long). This value is a delta from a UTC time-point, and is independent of the local time-zone1.
If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:
new Date() gives you a Date object initialized with the current date / time. The problem is that the Date API methods are mostly flawed ... and deprecated.
Calendar.getInstance() gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone. Other overloads allow you to use a specific Locale and/or TimeZone. Calendar works ... but the APIs are still cumbersome.
new org.joda.time.DateTime() gives you a Joda-time object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here. (But note that some people report that Joda time has performance issues.; e.g. https://stackoverflow.com/questions/6280829.)
in Java 8, calling java.time.LocalDateTime.now() and java.time.ZonedDateTime.now() will give you representations2 for the current date / time.
Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations.
With Java 8 and later, the standard java.time package is recommended. Joda time is now considered "obsolete", and the Joda maintainers are recommending that people migrate.3.
1 - System.currentTimeMillis() gives the "system" time. While it is normal practice for the system clock to be set to (nominal) UTC, there will be a difference (a delta) between the local UTC clock and true UTC. The size of the delta depends on how well (and how often) the system's clock is synced with UTC.
2 - Note that LocalDateTime doesn't include a time zone. As the javadoc says: "It cannot represent an instant on the time-line without additional information such as an offset or time-zone."
3 - Note: your Java 8 code won't break if you don't migrate, but the Joda codebase may eventually stop getting bug fixes and other patches. As of 2020-02, an official "end of life" for Joda has not been announced, and the Joda APIs have not been marked as Deprecated.
(Attention: only for use with Java versions <8. For Java 8+ check other replies.)
If you just need to output a time stamp in format YYYY.MM.DD-HH.MM.SS (very frequent case) then here's the way to do it:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
If you want the current date as String, try this:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
or
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
tl;dr
Instant.now() // Capture the current moment in UTC, with a resolution of nanoseconds. Returns a `Instant` object.
… or …
ZonedDateTime.now( // Capture the current moment as seen in…
ZoneId.of( "America/Montreal" ) // … the wall-clock time used by the people of a particular region (a time zone).
) // Returns a `ZonedDateTime` object.
java.time
A few of the Answers mention that java.time classes are the modern replacement for the troublesome old legacy date-time classes bundled with the earliest versions of Java. Below is a bit more information.
Time zone
The other Answers fail to explain how a time zone is crucial in determining the current date and time. For any given moment, the date and the time vary around the globe by zone. For example, a few minutes after midnight is a new day in Paris France while still being “yesterday” in Montréal Québec.
Instant
Much of your business logic and data storage/exchange should be done in UTC, as a best practice.
To get the current moment in UTC with a resolution in nanoseconds, use Instant class. Conventional computer hardware clocks are limited in their accuracy, so the current moment may be captured in milliseconds or microseconds rather than nanoseconds.
Instant instant = Instant.now();
ZonedDateTime
You can adjust that Instant into other time zones. Apply a ZoneId object to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
We can skip the Instant and get the current ZonedDateTime directly.
ZonedDateTime zdt = ZonedDateTime.now( z );
Always pass that optional time zone argument. If omitted, your JVM’s current default time zone is applied. The default can change at any moment, even during runtime. Do not subject your app to an externality out of your control. Always specify the desired/expected time zone.
ZonedDateTime do_Not_Do_This = ZonedDateTime.now(); // BAD - Never rely implicitly on the current default time zone.
You can later extract an Instant from the ZonedDateTime.
Instant instant = zdt.toInstant();
Always use an Instant or ZonedDateTime rather than a LocalDateTime when you want an actual moment on the timeline. The Local… types purposely have no concept of time zone so they represent only a rough idea of a possible moment. To get an actual moment you must assign a time zone to transform the Local… types into a ZonedDateTime and thereby make it meaningful.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z ); // Always pass a time zone.
Strings
To generate a String representing the date-time value, simply call toString on the java.time classes for the standard ISO 8601 formats.
String output = myLocalDate.toString(); // 2016-09-23
… or …
String output = zdt.toString(); // 2016-09-23T12:34:56.789+03:00[America/Montreal]
The ZonedDateTime class extends the standard format by wisely appending the name of the time zone in square brackets.
For other formats, search Stack Overflow for many Questions and Answers on the DateTimeFormatter class.
Avoid LocalDateTime
Contrary to the comment on the Question by RamanSB, you should not use LocalDateTime class for the current date-time.
The LocalDateTime purposely lacks any time zone or offset-from-UTC information. So, this is not appropriate when you are tracking a specific moment on the timeline. Certainly not appropriate for capturing the current moment.
A LocalDateTime has only a date and a time-of-day such as "noon on 23rd of January 2020", but we have no idea if that is noon in Tokyo Japan or noon in Toledo Ohio US, two different moments many hours apart.
The “Local” wording is counter-intuitive. It means any locality rather than any one specific locality. For example Christmas this year starts at midnight on the 25th of December: 2017-12-25T00:00:00, to be represented as a LocalDateTime. But this means midnight at various points around the globe at different times. Midnight happens first in Kiribati, later in New Zealand, hours more later in India, and so on, with several more hours passing before Christmas begins in France when the kids in Canada are still awaiting that day. Each one of these Christmas-start points would be represented as a separate ZonedDateTime.
From outside your system
If you cannot trust your system clock, see Java: Get current Date and Time from Server not System clock and my Answer.
java.time.Clock
To harness an alternate supplier of the current moment, write a subclass of the abstract java.time.Clock class.
You can pass your Clock implementation as an argument to the various java.time methods. For example, Instant.now( clock ).
Instant instant = Instant.now( yourClockGoesHere ) ;
For testing purposes, note the alternate implementations of Clock available statically from Clock itself: fixed, offset, tick, and more.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as 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.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
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 6 and Java SE 7
Most 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.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project 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.
In Java 8 it is:
LocalDateTime.now()
and in case you need time zone info:
ZonedDateTime.now()
and in case you want to print fancy formatted string:
System.out.println(ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME))
Just create a Date object...
import java.util.Date;
Date date = new Date();
// 2015/09/27 15:07:53
System.out.println( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()) );
// 15:07:53
System.out.println( new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()) );
// 09/28/2015
System.out.println(new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime()));
// 20150928_161823
System.out.println( new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()) );
// Mon Sep 28 16:24:28 CEST 2015
System.out.println( Calendar.getInstance().getTime() );
// Mon Sep 28 16:24:51 CEST 2015
System.out.println( new Date(System.currentTimeMillis()) );
// Mon Sep 28
System.out.println( new Date().toString().substring(0, 10) );
// 2015-09-28
System.out.println( new java.sql.Date(System.currentTimeMillis()) );
// 14:32:26
Date d = new Date();
System.out.println( (d.getTime() / 1000 / 60 / 60) % 24 + ":" + (d.getTime() / 1000 / 60) % 60 + ":" + (d.getTime() / 1000) % 60 );
// 2015-09-28 17:12:35.584
System.out.println( new Timestamp(System.currentTimeMillis()) );
// Java 8
// 2015-09-28T16:16:23.308+02:00[Europe/Belgrade]
System.out.println( ZonedDateTime.now() );
// Mon, 28 Sep 2015 16:16:23 +0200
System.out.println( ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME) );
// 2015-09-28
System.out.println( LocalDate.now(ZoneId.of("Europe/Paris")) ); // rest zones id in ZoneId class
// 16
System.out.println( LocalTime.now().getHour() );
// 2015-09-28T16:16:23.315
System.out.println( LocalDateTime.now() );
Use:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp );
(It's working.)
There are many different methods:
System.currentTimeMillis()
Date
Calendar
Create object of date and simply print it down.
Date d = new Date(System.currentTimeMillis());
System.out.print(d);
java.util.Date date = new java.util.Date();
It's automatically populated with the time it's instantiated.
Similar to above solutions. But I always find myself looking for this chunk of code:
Date date=Calendar.getInstance().getTime();
System.out.println(date);
For java.util.Date, just create a new Date()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43
For java.util.Calendar, uses Calendar.getInstance()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43
For java.time.LocalDateTime, uses LocalDateTime.now()
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); //2016/11/16 12:08:43
For java.time.LocalDate, uses LocalDate.now()
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //2016/11/16
Reference: https://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
1st Understand the java.util.Date class
1.1 How to obtain current Date
import java.util.Date;
class Demostration{
public static void main(String[]args){
Date date = new Date(); // date object
System.out.println(date); // Try to print the date object
}
}
1.2 How to use getTime() method
import java.util.Date;
public class Main {
public static void main(String[]args){
Date date = new Date();
long timeInMilliSeconds = date.getTime();
System.out.println(timeInMilliSeconds);
}
}
This will return the number of milliseconds since January 1, 1970, 00:00:00 GMT for time comparison purposes.
1.3 How to format time using SimpleDateFormat class
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
class Demostration{
public static void main(String[]args){
Date date=new Date();
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
String formattedDate=dateFormat.format(date);
System.out.println(formattedDate);
}
}
Also try using different format patterns like "yyyy-MM-dd hh:mm:ss" and select desired pattern. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
2nd Understand the java.util.Calendar class
2.1 Using Calendar Class to obtain current time stamp
import java.util.Calendar;
class Demostration{
public static void main(String[]args){
Calendar calendar=Calendar.getInstance();
System.out.println(calendar.getTime());
}
}
2.2 Try using setTime and other set methods for set calendar to different date.
Source: http://javau91.blogspot.com/
Have you looked at java.util.Date? It is exactly what you want.
Java 8 or above
LocalDateTime.now() and ZonedDateTime.now()
I find this to be the best way:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); // 2014/08/06 16:00:22
Have a look at the Date class. There's also the newer Calendar class which is the preferred method of doing many date / time operations (a lot of the methods on Date have been deprecated.)
If you just want the current date, then either create a new Date object or call Calendar.getInstance();.
As mentioned the basic Date() can do what you need in terms of getting the current time. In my recent experience working heavily with Java dates there are a lot of oddities with the built in classes (as well as deprecation of many of the Date class methods). One oddity that stood out to me was that months are 0 index based which from a technical standpoint makes sense, but in real terms can be very confusing.
If you are only concerned with the current date that should suffice - however if you intend to do a lot of manipulating/calculations with dates it could be very beneficial to use a third party library (so many exist because many Java developers have been unsatisfied with the built in functionality).
I second Stephen C's recommendation as I have found Joda-time to be very useful in simplifying my work with dates, it is also very well documented and you can find many useful examples throughout the web. I even ended up writing a static wrapper class (as DateUtils) which I use to consolidate and simplify all of my common date manipulation.
Use:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd::HH:mm:ss");
System.out.println(sdf.format(System.currentTimeMillis()));
The print statement will print the time when it is called and not when the SimpleDateFormat was created. So it can be called repeatedly without creating any new objects.
System.out.println( new SimpleDateFormat("yyyy:MM:dd - hh:mm:ss a").format(Calendar.getInstance().getTime()) );
//2018:02:10 - 05:04:20 PM
date/time with AM/PM
New Data-Time API is introduced with the dawn of Java 8. This is due
to following issues that were caused in the old data-time API.
Difficult to handle time zone : need to write lot of code to deal with
time zones.
Not Thread Safe : java.util.Date is not thread safe.
So have a look around with Java 8
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;
public class DataTimeChecker {
public static void main(String args[]) {
DataTimeChecker dateTimeChecker = new DataTimeChecker();
dateTimeChecker.DateTime();
}
public void DateTime() {
// Get the current date and time
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("Current DateTime: " + currentTime);
LocalDate date1 = currentTime.toLocalDate();
System.out.println("Date : " + date1);
Month month = currentTime.getMonth();
int day = currentTime.getDayOfMonth();
int seconds = currentTime.getSecond();
System.out.println("Month : " + month);
System.out.println("Day : " + day);
System.out.println("Seconds : " + seconds);
LocalDateTime date2 = currentTime.withDayOfMonth(17).withYear(2018);
System.out.println("Date : " + date2);
//Prints 17 May 2018
LocalDate date3 = LocalDate.of(2018, Month.MAY, 17);
System.out.println("Date : " + date3);
//Prints 04 hour 45 minutes
LocalTime date4 = LocalTime.of(4, 45);
System.out.println("Date : " + date4);
// Convert to a String
LocalTime date5 = LocalTime.parse("20:15:30");
System.out.println("Date : " + date5);
}
}
Output of the coding above :
Current DateTime: 2018-05-17T04:40:34.603
Date : 2018-05-17
Month : MAY
Day : 17
Seconds : 34
Date : 2018-05-17T04:40:34.603
Date : 2018-05-17
Date : 04:45
Date : 20:15:30
I created this methods, it works for me...
public String GetDay() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd")));
}
public String GetNameOfTheDay() {
return String.valueOf(LocalDateTime.now().getDayOfWeek());
}
public String GetMonth() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM")));
}
public String GetNameOfTheMonth() {
return String.valueOf(LocalDateTime.now().getMonth());
}
public String GetYear() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy")));
}
public boolean isLeapYear(long year) {
return Year.isLeap(year);
}
public String GetDate() {
return GetDay() + "/" + GetMonth() + "/" + GetYear();
}
public String Get12HHour() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh")));
}
public String Get24HHour() {
return String.valueOf(LocalDateTime.now().getHour());
}
public String GetMinutes() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("mm")));
}
public String GetSeconds() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("ss")));
}
public String Get24HTime() {
return Get24HHour() + ":" + GetMinutes();
}
public String Get24HFullTime() {
return Get24HHour() + ":" + GetMinutes() + ":" + GetSeconds();
}
public String Get12HTime() {
return Get12HHour() + ":" + GetMinutes();
}
public String Get12HFullTime() {
return Get12HHour() + ":" + GetMinutes() + ":" + GetSeconds();
}
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Current Date: " + ft.format(dNow));
}
}
you can use date for fet current data. so using SimpleDateFormat get format
just try this code:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CurrentTimeDateCalendar {
public static void getCurrentTimeUsingDate() {
Date date = new Date();
String strDateFormat = "hh:mm:ss a";
DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
String formattedDate= dateFormat.format(date);
System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate);
}
public static void getCurrentTimeUsingCalendar() {
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String formattedDate=dateFormat.format(date);
System.out.println("Current time of the day using Calendar - 24 hour format: "+ formattedDate);
}
}
which the sample output is:
Current time of the day using Date - 12 hour format: 11:13:01 PM
Current time of the day using Calendar - 24 hour format: 23:13:01
more information on:
Getting Current Date Time in Java
Current Date using java 8:
First, let's use java.time.LocalDate to get the current system date:
LocalDate localDate = LocalDate.now();
To get the date in any other timezone we can use LocalDate.now(ZoneId):
LocalDate localDate = LocalDate.now(ZoneId.of("GMT+02:30"));
We can also use java.time.LocalDateTime to get an instance of LocalDate:
LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = localDateTime.toLocalDate();
You can use Date object and format by yourself. It is hard to format and need more codes, as a example,
Date dateInstance = new Date();
int year = dateInstance.getYear()+1900;//Returns:the year represented by this date, minus 1900.
int date = dateInstance.getDate();
int month = dateInstance.getMonth();
int day = dateInstance.getDay();
int hours = dateInstance.getHours();
int min = dateInstance.getMinutes();
int sec = dateInstance.getSeconds();
String dayOfWeek = "";
switch(day){
case 0:
dayOfWeek = "Sunday";
break;
case 1:
dayOfWeek = "Monday";
break;
case 2:
dayOfWeek = "Tuesday";
break;
case 3:
dayOfWeek = "Wednesday";
break;
case 4:
dayOfWeek = "Thursday";
break;
case 5:
dayOfWeek = "Friday";
break;
case 6:
dayOfWeek = "Saturday";
break;
}
System.out.println("Date: " + year +"-"+ month + "-" + date + " "+ dayOfWeek);
System.out.println("Time: " + hours +":"+ min + ":" + sec);
output:
Date: 2017-6-23 Sunday
Time: 14:6:20
As you can see this is the worst way you can do it and according to oracle documentation it is deprecated.
Oracle doc:
The class Date represents a specific instant in time, with millisecond
precision.
Prior to JDK 1.1, the class Date had two additional functions. It
allowed the interpretation of dates as year, month, day, hour, minute,
and second values. It also allowed the formatting and parsing of date
strings. Unfortunately, the API for these functions was not amenable
to internationalization. As of JDK 1.1, the Calendar class should be
used to convert between dates and time fields and the DateFormat class
should be used to format and parse date strings. The corresponding
methods in Date are deprecated.
So alternatively, you can use Calendar class,
Calendar.YEAR;
//and lot more
To get current time, you can use:
Calendar rightNow = Calendar.getInstance();
Doc:
Like other locale-sensitive classes, Calendar provides a class method,
getInstance, for getting a generally useful object of this type.
Calendar's getInstance method returns a Calendar object whose calendar
fields have been initialized with the current date and time
Below code for to get only date
Date rightNow = Calendar.getInstance().getTime();
System.out.println(rightNow);
Also, Calendar class have Subclasses. GregorianCalendar is a one of them and concrete subclass of Calendar and provides the standard calendar system used by most of the world.
Example using GregorianCalendar:
Calendar cal = new GregorianCalendar();
int hours = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int ap = cal.get(Calendar.AM_PM);
String amVSpm;
if(ap == 0){
amVSpm = "AM";
}else{
amVSpm = "PM";
}
String timer = hours + "-" + minute + "-" + second + " " +amVSpm;
System.out.println(timer);
You can use SimpleDateFormat, simple and quick way to format date:
String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date());
System.out.println(date);
Read this Jakob Jenkov tutorial: Java SimpleDateFormat.
As others mentioned, when we need to do manipulation from dates, we didn't had simple and best way or we couldn't satisfied built in classes, APIs.
As a example, When we need to get different between two dates, when we need to compare two dates(there is in-built method also for this) and many more. We had to use third party libraries. One of the good and popular one is Joda Time.
Also read:
How to get properly current date and time in Joda-Time?
JodaTime - how to get current time in UTC
Examples for JodaTime.
Download Joda
.
The happiest thing is now(in java 8), no one need to download and use libraries for any reasons. A simple example to get current date & time in Java 8,
LocalTime localTime = LocalTime.now();
System.out.println(localTime);
//with time zone
LocalTime localTimeWtZone = LocalTime.now(ZoneId.of("GMT+02:30"));
System.out.println(localTimeWtZone);
One of the good blog post to read about Java 8 date.
And keep remeber to find out more about Java date and time because there is lot more ways and/or useful ways that you can get/use.
Oracle tutorials for date & time.
Oracle tutorials for formatter.
Lesson: Standard Calendar.
EDIT:
According to #BasilBourque comment, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.
I'll go ahead and throw this answer in because it is all I needed when I had the same question:
Date currentDate = new Date(System.currentTimeMillis());
currentDate is now your current date in a Java Date object.