How to find current date in java. I found a lot but every time i got same command
Date d = new Date(); or something similar
Every such command returns a date of 1970 year.
I fail to understand, Whats the benefit of this getting a date of 1970 ?
Is there any way where i can get current time and add a second into it.
My real purpose is to convert a long value into Date and add a second in it.
5:40:12 should give me 5:40:13 after adding a second.
Any help would be appreciated as i am fed up getting 1970 date.
My real purpose is to convert a long value into Date and add a second in it. 5:40:12 should give me 5:40:13 after adding a second
The troublesome java.util.Date class is now legacy, supplanted by the java.time classes.
Instant.ofEpochMilli( yourLongIntegerGoesHere ) // A moment on the timeline in UTC represented a count of nanoseconds since the epoch of `1970-01-01T00:00:00Z`.
.atZone( ZoneId.of( "Pacific/Auckland" ) // Time zone for the region whose wall-clock time you want to see.
.plusSeconds( 1 )
.toLocalTime() // Extract just the time-of-day without date and without time zone.
.toString() // Generate a string representing the time-of-day value in standard ISO 8601 format.
05:40:13
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.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
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
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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.
Java.Util.Date class is deprecated, I would recommend using
Java.Util.Calendar instead.
If you're looking to add a second to Current date, try something like this:
Calendar currentTime = Calendar.getInstance(); // gets a calendar using the default time zone and locale.
calendar.add(currentTime.SECOND, 1);
System.out.println(currentTime.getTime());
BUT, the reason why you are receiving a 1970 date when using the Date class is because that class works with milliseconds, so you must multiply the long value by 1000 in order for it to convert to a date, here's an example.
Date currentDate = new Date( YourLongValue * 1000);
Related
java.sql.Date date = java.sql.Date.valueOf("1900-01-01");
org.joda.time.LocalDate localDate = new org.joda.time.LocalDate(date);
Based above code, I did some tests as below:
Question #1 why do I get different localDate object with same timezone?
If I change local timezone to UTC+8 Singapore Timezone, will get 1899-12-31
If I change local timezone to UTC+8 China Timezone, will get 1900-01-01
Question #2 why do I get same time with different timezone?
If I change local timezone to UTC-8 America/Los_Angeles Timezone, will get 1900-01-01
If I change local timezone to UTC+8 China Timezone, will get 1900-01-01
Could someone help clarify that?? it is little bit confused.
In 1900, Singpore's offset is UTC +6:55:25, so when you create date 1900-01-01 in Singapore time zone, it should be 1899-12-31T17:04:35Z[UTC] as below:
java.time.ZonedDateTime localDateTime = ZonedDateTime.of(1900, 01, 01, 0,
0, 0, 0, ZoneId.of("Singapore"));
System.out.println(localDateTime.withZoneSameInstant(ZoneId.of("UTC")));
// 1899-12-31T17:04:35Z[UTC]
However, when you use java.sql.Date, it use wrong offset UTC +08:00:
TimeZone.setDefault(TimeZone.getTimeZone("Singapore"));
java.sql.Date date = java.sql.Date.valueOf("1900-01-01");
java.time.Instant instant = Instant.ofEpochMilli(date.getTime());
System.out.println(instant); // 1899-12-31T16:00:00Z
and when you create org.joda.time.LocalDateTime with this wrong value, Joda use UTC +6:55:25 as offset, resulting in a date time 1899-12-31T16:00:00 + 6:55:25:
org.joda.time.LocalDateTime singaporeDateTime = new org.joda.time.LocalDateTime(date);
System.out.println(singaporeDateTime); // 1899-12-31T22:55:25.000
You can use the similar approach to check the result of Shanghai and Los Angelas, the point is, avoid using java.sql.Date and other deprecated date time related classes. Use java.time instead if you are working with java8 or higher.
tl;dr
java.time.LocalDate
.of(
1900 ,
Month.JANUARY ,
1
) ;
Avoid legacy date-time classes
You are using a terrible old class java.sql.Date that was badly designed with flawed hacks. Among its problems is that it pretends to represent a date-only value but actually holds a time-of-day. It even holds a time zone deep inside, though without getter or setter. Never use this class. Supplanted years ago by the java.time.LocalDate class.
The Joda-Time project too is supplanted by the java.time classes. The project is in maintenance mode, receiving updates and critical bug fixes but no new feature work. The project advises migration to the java.time classes. Migration is easy as they share similar concepts, both having been led by the same man, Stephen Colebourne.
java.time.LocalDate
Use java.time.LocalDate when you want a date-only value without time-of-day and without time zone. All your problems raised in your Question go away.
java.time.LocalDate ld = LocalDate.of( 1900 , Month.JANUARY , 1 ) ; // Simply a year-month-day date, no problems, no issues, no confusion.
ld.toString(): 1900-01-01
Also notice that java.time uses sane numbering where 2018 means the year 2018, and 1-12 means January-December. This is in distinct contrast to the troublesome legacy classes.
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.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
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.
I'm looking to see if there is a better way in obtaining the same result as the following code:
Calendar date = Calendar.getInstance();
date.setTimeInMillis(System.currentTimeMillis());
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
I'm using this to be able to compare the difference in days between two dates. I am currently coding for target API 24 and am not interested in using Joda Time for such a simple task.
I've come up with the following function, but would love to hear if there is a simpler, perhaps built in, method for either zeroing out the date or an entire different method for getting the amount of days between two dates.
private long getFlatDateInMillis() {
Calendar currentDate = Calendar.getInstance();
currentDate.setTimeInMillis(System.currentTimeMillis());
currentDate.set(Calendar.HOUR_OF_DAY, 0);
currentDate.set(Calendar.MINUTE, 0);
currentDate.set(Calendar.SECOND, 0);
currentDate.set(Calendar.MILLISECOND, 0);
return currentDate.getTimeInMillis();
}
That way, I could quickly use:
Calendar date = getFlatDateInMillis();
I just want to make sure I'm not missing anything that is simpler, already pre-defined.
Thank you!
The correct way to do this is with the java.time.LocalDate class. It stores only the date, not the time, and it has a now() static method, which returns the current day.
LocalDate today = LocalDate.now();
If you're looking at Android, this was added at API level 26, but there are other ways of using the "new style" date classes with Android, such as the ThreeTen-Backport library.
tl;dr
ChronoUnit.DAYS.between( // Calculate elapsed time between a pair of `LocalDate` date-only objects. Returns a total number of elapsed days.
( (GregorianCalendar) myJavaUtilCal ) // Cast your legacy `java.util.Calendar` object to the subclass `java.util.GregorianCalendar`, also legacy.
.toZonedDateTime() // Convert from legacy `GregorianCalendar` to modern `ZonedDateTime` class.
.toLocalDate() , // Extract the date-only value, a `LocalDate`, lacking time-of-day and lacking time zone.
otherLocalDate // Compare to some other `LocalDate` object.
) // Returns a `long` number of days. Uses Half-Open approach where the beginning is *inclusive* while the ending is *exclusive*.
Details
The Answer by Kareem is correct. Some more thoughts here.
Is there a better way to zero out Calendar date?
Yes, there is a better way: don’t.
Trying to clear out the time-of-day on a date+time types is the wrong approach; use a date-only type instead (LocalDate).
And don’t use the troublesome old legacy classes such as Calendar, Date, SimpleDateFormat as they are now supplanted by the java.time classes.
the difference in days between two dates
First convert your legacy Calendar object to the modern ZonedDateTime class. To convert, call new methods added to the old classes.
GregorianCalendar myGregCal = (GregorianCalendar) myJavaUtilCal ; // Cast from superclass to subclass.
ZonedDateTime zdt = myGregCal.toZonedDateTime() ; // Convert from legacy class to modern class.
Extract the date-only value.
LocalDate ld = zdt.toLocalDate() ; // Extract date-only object from date-time object.
Calculate elapsed time in days
long days = ChronoUnit.DAYS.between( ld , otherLd ) ;
Or represent the elapsed time as a Period.
Period p = Period.between( ld , otherLd ) ;
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.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
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, and later
Built-in.
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
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.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.
EDIT: Thanks to Basil and Kareem, I've updated to the following code (so, so much easier):
Added to gradle.build:
compile 'com.jakewharton.threetenabp:threetenabp:1.0.5'
Then, in my activity, etc,
AndroidThreeTen.init(this);
LocalDate today = LocalDate.now();
LocalDate anotherDay = LocalDate.of(2019, 3, 25);
long dayDifference = ChronoUnit.DAYS.between(today, anotherDay); //dayDifference = 365
One thing of note is that Calendar references months starting at 0 index, whereas LocalDate references months starting at 1 index.
I'm trying to use a Date String to select a string to be displayed in my android app.
The Code im using to GET Date:
Calendar TextCalendar = Calendar.getInstance();
SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String TextDate = DateFormat.format(TextCalendar.getTime());
The Code im imagining I need to select strings:
TextView MyTextView = (TextView) findViewByID(R.id.my_text_view);
MyTextView.setText ( "DateVariable" + "Comment" )
This code I imagine not to work because I tried but, the bit with "DateVariable" And "Comment" means I could have Strings in Strings.xml Named Each Date but I would have 2 Strings for each day because there is a TITLE String and A Comment String, so i could imagine the string names looking like this
<string name="2016-02-28-TITLE">TESTING20160228</string>
<string name="2016-02-28-COMMENT">TESTING20160228Comment</string>
<string name="2016-02-29-TITLE">....
and so on
If anyone has a better suggestion on how to proceed with this it would be greatly appreciated.
Thanks ~Alexander
Try this:
String s = TextDate + "-Comment";
getString(getResources().getIdentifier(s, "string", getPackageName()));
Time Zone
Determining the current date requires a time zone. The date is not simultaneously the same around the world. A new day dawns earlier in the east. For example, in the first few minutes after midnight in Paris, it is still “yesterday” in Montréal.
If omitted, your JVM’s current default time zone is implicitly applied. That default can may vary, even during runtime! Better to be explicit with your desired/expected time zone.
java.time
You are using old date-time classes that have been supplanted by the java.time framework built into Java 8 and later. Much of java.time is back-ported to Java 6 & 7 and further adapted to Android.
These java.time classes include the LocalDate class for date-only values lacking a time-of-day and time zone.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Your desired textual format complies with the ISO 8601 standard. The java.time classes use ISO 8601 by default when parsing/generating strings.
String output = today.toString() + "-Comment";
Java Naming
By the way, the code in your Question does not follow naming conventions. Class names should start with an uppercase while instance variable names should start with a lowercase.
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.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
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.
I have a date string
String s = "2014-09-01T19:22:43.000Z";
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(s);
But I get an exception:
Exception in thread "main" java.text.ParseException: Unparseable date: "2014-09-01T19:22:43.000Z"
How do I convert the above string to unix timestamp?
Thanks
tl;dr
How do I convert the above string to unix timestamp?
Instant.parse( "2014-09-01T19:22:43.000Z" )
.getEpochSecond()
java.time
The java.time.Instant class can parse your input string with its standard ISO 8601 format. No need to specify a formatting pattern.
Instant instant = Instant.parse( "2014-09-01T19:22:43.000Z" );
To get a count of milliseconds since the epoch of 1970:
long millisecondsSinceUnixEpoch = instant.toEpochMilli() ;
For whole seconds since epoch of 1970-01-01T00:00:00Z:
long secondsSinceUnixEpoch = instant.getEpochSecond() ;
Be aware of possible data loss when going to milliseconds or whole seconds. The java.time classes have nanosecond resolution, so any microseconds or nanoseconds present in the value will be truncated.
Joda-Time
Update The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.
The Joda-Time library makes this work easier. Your ISO 8601 compliant string can be fed directly to a Joda-Time constructor. The built-in parser expects ISO 8601.
DateTime dateTime = new DateTime( "2014-09-01T19:22:43.000Z" ) ;
Unix Timestamp
What do you mean by a Unix timestamp? Some people mean a count of whole seconds since the first moment of 1970 UTC (the Unix epoch) while ignoring leap seconds (see Unix Time). Some people mean a count of milliseconds or other resolution.
Note the use of a long primitive rather than the more common int.
For milliseconds, call getMillis().
long millisecondsSinceUnixEpoch = dateTime.getMillis();
For whole seconds, divide by 1,000. Consider if you want rounding or truncation of the fractional seconds.
Normally I would suggest passing a DateTimeZone object along with your string to the DateTime constructor. But no need if all you want is a count since epoch.
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.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
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
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.time classes.
For earlier Android, 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.
X is used for ISO 8601 time zone in SimpleDateFormat, not Z
Correct format is "yyyy-MM-dd'T'HH:mm:ss.SSSX"
I try to format a time interval using SimpleDateFormat.
import java.text.*;
import java.util.*;
public class DateFormatTest {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
long interval = 1000;
System.out.println("Interval in millis: " + interval);
System.out.println("Expected result: 00:00:01");
System.out.println("Result using Date and SimpleDateFormat: " +
sdf.format(new Date(interval)));
}
}
I get the following result:
Interval in millis: 1000
Expected result: 00:00:01
Result using Date and SimpleDateFormat: 01:00:01
I am in GMT+1 time zone. But it should not be reflected in the result.
Of course it can be solved with System.out.printf, but what I am searching is the reason.
I am in GMT+1 time zone. But should not be reflected in the result.
What makes you think so? new Date(0) is at 00:00AM GMT on Jan 1st 1970. So it is at 01:00AM if your default timezone is GMT + 1.
I am in GMT+1 time zone. But it should not be reflected in the result.
Then you should set the time zone in the SimpleDateFormat. SimpleDateFormat is doing exactly the right thing - it's formatting the instant in time (just after midnight UTC 1970) in the time zone it's working in.
To change the time zone, just use:
sdf.setTimeZone(TimeZone.getTimeZone("etc/UTC"));
It's not clear whether you should really be using SimpleDateFormat at all, though. You're not trying to format a date/time - you're trying to format an interval, given your variable name.
I suggest you use Joda Time which has a much richer type system, and will allow you to express what you really want.
Also, if you really want to use SimpleDateFormat, you probably want to use HH instead of hh in your format string. (hh is a 12-hour value, 1-12. You want 00:00:01, not 12:00:01.) hh is rarely appropriate when you don't also have an am/pm designator in your pattern.
Wrong data type
You are using the wrong class. You are trying to represent a duration of milliseconds and a time-of-day. Neither fits the Date class. That class represents a moment (a date, with time-of-day, in context of UTC).
Also, java.util.Date is a terrible class, designed by people who did not understand date-time handling. Now obsolete.
java.time
The modern solution uses java.time classes.
LocalTime
Specifically, LocalTime for a time-of-day using a generic 24-hour day, without a date, and without the context of a time zone or offset-from-UTC.
The start of a day for generic days is 00:00:00. We have a constant for that: LocalTime.MIN. But know that in various time zones, on various dates, the day may start at another time such as 01:00:00.
LocalTime lt = LocalTime.of( 15 , 30 ) ; // 3:30 PM.
Duration
To represent a span-of-time unattached to the timeline, on a scale of hours-minutes-seconds, use Duration class.
Duration d = Duration.ofMilliseconds( 1_000 ) ;
We can do math with date-time objects.
LocalTime lt = LocalTime.MIN.plus( d ) ;
You should know that java.time classes use a resolution of nanoseconds, much finer than the milliseconds used by the legacy date-time classes.
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.