I am having quarter end date of last quarter let it be 30-09-20 , the requirement is to find end date of next quarter i.e 31-12-20. I am using below code to do the same but is it giving wrong output in some scenarios. This solution should be correct for all quarters.
String str = "30-09-20";
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yy");
Date date = format.parse(str);
Date newDate = DateUtils.addMonths(date, 3);
System.out.println(newDate);//Dec 30 - It should be 31 Dec
To answer your question, I think you are looking for this :
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy");
LocalDate end = LocalDate.parse("30-09-20", formatter)
.plusMonths(3) // add three months to your date
.with(TemporalAdjusters.lastDayOfMonth()); // with the last day of the month
Note: don't use the legacy Date library, you tagged your question Java-8 which mean you can use java-time API.
Get last day of current quarter
#deHaar have reason, to get the end date of curent quarter, I would suggest to use :
public LocalDate lastDayFromDateQuarter(String date) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy");
LocalDate ld = LocalDate.parse(date, formatter);
int quarter = ld.get(IsoFields.QUARTER_OF_YEAR); // Get the Quarter, 1, 2, 3, 4
// Then create a new date with new quarter * 3 and last day of month
return ld.withMonth(quarter * 3).with(TemporalAdjusters.lastDayOfMonth());
}
Get last day of next quarter
To get the last day of the next quarter, then you just can add three months to your date like so :
public static LocalDate lastDayFromDateQuarter(String date) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy");
LocalDate ld = LocalDate.parse(date, formatter);
int quarter = ld.get(IsoFields.QUARTER_OF_YEAR);
return ld.withMonth(quarter * 3)
.plusMonths(3)
.with(TemporalAdjusters.lastDayOfMonth());
}
tl;dr
Use YearQuarter class from ThreeTen-Extra.
YearQuarter // A class available in the ThreeTen-Extra library.
.from( // Factory method rather than calling `new`.
LocalDate.of( 2020 , Month.SEPTEMBER , 30 ) // Returns a `LocalDate` object, represent a date-only value without a time-of-day and without a time zone.
) // Returns a `YearQuarter` object.
.plusQuarters( 1 ) // Perform date-math, resulting in a new `YearQuarter` object (per immutable objects pattern).
.atEndOfQuarter() // Determine the date of last day of this year-quarter.
.toString() // Generate text in standard ISO 8601 format.
2020-12-31
org.threeten.extra.YearQuarter
The ThreeTen-Extra library provides classes that extend the functionality of the java.time classes built into Java 8 and later. One of its classes is YearQuarter to represent a specific quarter in a specific year. The quarters are defined by calendar-year: Jan-Mar, Apr-June, July-Sept, Oct-Dec.
LocalDate localDate = LocalDate.of( 2020 , Month.SEPTEMBER , 30 ) ;
YearQuarter yearQuarter = YearQuarter.from( localDate ) ;
Move to the next quarter by adding one quarter to our current year-quarter.
The java.time and ThreeTen-Extra classes use immutable objects. So rather than alter ("mutate") the original object, when adding we produce a new object.
YearQuarter followingYearQuarter = yearQuarter.plusQuarters( 1 ) ;
Determine the last day of that quarter.
LocalDate lastDateOfFollowingYearQuarter = followingYearQuarter.atEndOfQuarter() ;
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.
Here is my version (hopefully more readable) of finding the last day of next quarter for any date:
public LocalDate lastDayOfNextQuarter(LocalDate date) {
Month firstMonthOfCurrentQuarter = date.getMonth().firstMonthOfQuarter();
LocalDate lastMonthOfCurrentQuarter = date.with(firstMonthOfCurrentQuarter.plus(2));
LocalDate lastMonthOfNextQuarter = lastMonthOfCurrentQuarter.plusMonths(3);
return lastMonthOfNextQuarter.with(lastDayOfMonth());
}
And a corresponding test method:
#ParameterizedTest
#CsvSource({"2020-01-01,2020-06-30", "2020-02-01,2020-06-30", "2020-03-01,2020-06-30", "2020-04-10,2020-09-30",
"2020-05-10,2020-09-30", "2020-06-10,2020-09-30", "2020-07-20,2020-12-31", "2020-08-20,2020-12-31",
"2020-09-30,2020-12-31", "2020-10-30,2021-03-31", "2020-11-30,2021-03-31", "2020-12-31,2021-03-31"})
public void testLastDayOfNextQuarter(LocalDate input, LocalDate expected) {
LocalDate result = timeUtils.lastDayOfNextQuarter(input);
assertEquals(expected, result);
}
You can manipulate quarter easily with TemporalAdjusters. See below:
LocalDate localDate = LocalDate.now();
LocalDate firstDayOfQuarter = localDate.with(IsoFields.DAY_OF_QUARTER, 1);
System.out.println(firstDayOfQuarter);
LocalDate lastDayOfQuarter = firstDayOfQuarter.plusMonths(2).with(TemporalAdjusters.lastDayOfMonth());
System.out.println(lastDayOfQuarter);
LocalDate firstDateOfNextQuarter = lastDayOfQuarter.plusDays(1);
LocalDate lastDayOfNextQuarter = firstDateOfNextQuarter.plusMonths(2).with(TemporalAdjusters.lastDayOfMonth());
System.out.println(lastDayOfNextQuarter);
Output:
2020-01-01
2020-03-31
2020-06-30
You can use a Calendar instance to get the last day of the month.
String str = "30-12-20";
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yy");
Date date = format.parse(str);
Date newDate = DateUtils.addMonths(date, 3);
Calendar cal = new GregorianCalendar();
cal.setTime(newDate);
System.out.println(cal.getActualMaximum(Calendar.DAY_OF_MONTH));
Related
Hi i am trying to get the current year in the below code however it is returning a 1970 year instead of 2020 last month this was working correctly but since we in January 2020, it is now returning a date from 1970, please assist
public String firstDateOfNextMonth(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar today = Calendar.getInstance();
Calendar next = Calendar.getInstance();
today.clear();
Date date;
next.clear();
next.set(Calendar.YEAR, today.get(Calendar.YEAR));
next.set(Calendar.MONTH, today.get(Calendar.MONTH)+ 1);
next.set(Calendar.DAY_OF_MONTH, 1);
date = next.getTime();
Log.d(TAG, "The Date: " + dateFormat.format(date));
return dateFormat.format(date);
}
If you have Java 8 or above, then you have java.time and you won't have to rely on outdated datetime implementations and you can do it this way:
public static String getFirstOfNextMonth() {
// get a reference to today
LocalDate today = LocalDate.now();
// having today,
LocalDate firstOfNextMonth = today
// add one to the month
.withMonth(today.getMonthValue() + 1)
// and take the first day of that month
.withDayOfMonth(1);
// then return it as formatted String
return firstOfNextMonth.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
which prints the following when called today (2020-01-03) like System.out.println(getFirstOfNextMonth());:
2020-02-01
You might have to involve an external library, the ThreeTenAbp if you want it to work in Android below API level 26. Its use is explained in this question.
not sure why the today date gets cleared, remove today.clear() at line 4
today.clear(); initalize all elements of a date with the value 0
removing this line will give you the right answer
tl;dr
LocalDate // Represent a date-only value without a time-of-day and without a time zone.
.now( // Determine the current date as seen through the wall-clock time used by people in certain region (a time zone).
ZoneId.of( "America/Montreal" ) // Real time zone names have names in the format of `Continent/Region`. Never use 2-4 letter pseudo-zones such as `IST`, `PST`, or `CST`, which are neither standardized nor unique.
) // Return a `LocalDate`.
.with( // Move from one date another by passing a `TemporalAdjuster` implementation.
TemporalAdjusters // Class providing several implementations of `TemporalAdjuster`.
.firstDayOfNextMonth() // This adjuster finds the date of the first of next month, as its name suggests.
) // Returns another `LocalDate` object. The original `LocalDate` object is unaltered.
.toString() // Generate text in standard ISO 8601 format of YYYY-MM-DD.
See this code run live at IdeOne.com.
2020-02-01
Details
You are using terrible date-time classes that were made obsolete years ago by the unanimous adoption of JSR 310 defining the java.time classes.
The Answer by deHaar is correct. Here is an even shorter solution.
TemporalAdjuster
To move from one date to another, the java.time classes include the TemporalAdjuster interface. Pass one of these objects to the with method found on many of the other java.time classes.
TemporalAdjusters.firstDayOfNextMonth()
Several implementations of that interface are found in the class TemporalAdjusters (note the s plural). One of those is firstDayOfNextMonth(), just what you need.
Get today's date. A time zone is required, as for any given moment the date varies around the globe by time zone. If omitted, your JVM's current default time zone is implicitly applied. Better to be explicit.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalDate today = LocalDate.now( z ) ;
Get your TemporalAdjuster object.
TemporalAdjuster ta = TemporalAdjusters.firstDayOfNextMonth() ;
Apply that adjuster to get another LocalDate object. Note that java.time classes are immutable by design. So we get a new object rather than altering the original.
LocalDate firstOfNextMonth = today.with( ta ) ;
We can shorten this code to a one-liner, if desired.
LocalDate firstOfNextMonth =
LocalDate
.now(
ZoneId.of( "Africa/Tunis" )
)
.with(
TemporalAdjusters.firstDayOfNextMonth()
)
;
Text
Your desired output format of YYYY-MM-DD complies with the ISO 8601 standard used by default in the java.time classes when parsing/generating text. So no formatting pattern need be specified.
String output = firstOfNextMonth.toString() ;
2020-02-01
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.
You are using Calendar.clear() which clears all the fields of your calendar, and essentially reverts it to 1/1/1970 (epoch time 0).
remove today.clear() and you'll get the correct answer
see more here
Remove next.clear();. As Calendar next= Calendar.getInstance(); initiates next with the current date, in your cases Fri Jan 03 2020 15:07:53. And when you do next.clear(), it sets to the inital epoch.
Epoch, also known as Unix timestamps, is the number of seconds (not
milliseconds!) that have elapsed since January 1, 1970 at 00:00:00 GMT
(1970-01-01 00:00:00 GMT).
What I'm looking for :
When any date is selected, output the relevant string of day which is "Mon, Tue,...,Sun"
What I have done :
I have an edit text view which is to select a date and the format of date is MM/dd/YY.
This works well.
What is going wrong:
Initially, when I select a date(not current date) string output the "current day" Not the one I selected now. When I select another date, string shows the previously(in this case the one selected initially) selected day. Simply it is like storing the previous day string.
My code :
Datelistner = CustomDateTimePicker.getCustomDatePicker(DateEditText,null,myCalander);
DateEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),Datelistner,
myCalander.get(Calendar.YEAR),
myCalander.get(Calendar.MONTH),
myCalander.get(Calendar.DAY_OF_MONTH));
selectedDateIndex = myCalander.get(Calendar.DAY_OF_WEEK);
ArrayList<String> dateString = new ArrayList<String>();
dateString.add("Sun");
dateString.add("Mon");
dateString.add("Tue");
dateString.add("Wed");
dateString.add("Thu");
dateString.add("Fri");
dateString.add("Sat");
selectedDate = dateString.get(selectedDateIndex - 1);
datePickerDialog.getDatePicker().setMinDate(new Date().getTime());
datePickerDialog.setCancelable(false);
datePickerDialog.show();
}
});
updateLabelAddEvent();
private void updateLabelAddEvent() {
String myFormat = "MM/dd/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());
DateEditText.setText(sdf.format(myCalander.getTime()));
}
I have already defined the string variable(selectedDate) and int variable (selectedDateIndex) as global (during oncreate).
I'm just wondering whether how to fix this.
Zero-based counting
The terrible Calendar class has many poor design decisions. One of those is counting day-of-week as zero-based. So first day is 0, last is 7. Looks like you are subtracting one to get a zero-based index into your array, not realizing you already have a zero-based number. So stop subtracting.
Week definition varies
Another problem is that the definition of a week in Calendar varies by locale.
java.time
More important, you should be using the modern java.time classes rather than the bloody awful legacy date-time classes.
Current moment by zone
Get current date-time as seen in a time zone.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Generate text
Get the day of week using the DayOfWeek enum built into Java.
DayOfWeek dow = zdt.getDayOfWeek() ;
Automatically localize. No need for that array of yours listing day names.
Specify a Locale to determine the human language and cultural norms for localization.
Locale locale = Locale.CANADA_FRENCH ; // Or Locale.US or such.
String output = dow.getDisplayName( TextStyle.SHORT , locale ) ;
Converting
To interoperate with old code not yet updated to java.time, convert. Call new to/from methods added to the old classes.
ZonedDateTime class replaces GregorianCalendar, the usual concrete class behind Calendar. So cast.
Calendar c = GregorianCalendar.from( zdt ) ;
And:
ZonedDateTime zdt = ( ( GregorianCalendar ) c ).toZonedDateTime() ;
I see you also use java.util.Date. Replaced by Instant to represent a moment in UTC.
Instant instant = myJavaUtilDate.toInstant() ;
And:
java.util.Date myJavaUtilDate = java.util.Date.from( instant ) ;
You can get an Instant from your ZonedDateTime.
Instant instant = zdt.toInstant() ;
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….
We have a java code snippet here
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
Date date = new Date();
int days = 5;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String strDate= formatter.format(date.getTime() + (days*86400000));
System.out.println(strDate);
}
}
to add n no. of days to today's date. The result will be correct upto n=24 but gives previous month' after n=24. Why it is so?
The problem is the the int is overflowing
consider
int days = 25;
int d = days*86400000;
System.out.println(d);
try
int days = 25;
long d = days*86400000L;
System.out.println(d);
tl;dr
LocalDate // Represent a date-only, without a time-of-day and without a time zone.
.now() // Capture the current date, as seen through your JVM’s current default time zone. Better to pass a `ZoneId` as the optional argument.
.plusDays( 5 ) // Add five days, returning a new `LocalDate` object. Per the Immutable Objects pattern, a new object is produced rather than changing (“mutating”) the original.
.format( // Generate text representing the date value of our `LocalDate` object.
DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) // Define a formatting pattern to suit your taste. Or call the `.ofLocalized…` methods to localize automatically.
) // Returns a `String`.
java.time
Date class represents a moment in UTC, a date with a time-of-day, and an offset-from-UTC of zero. Wrong class to use when working with date-only values.
Avoid using the terrible old legacy date-time classes such as Calendar, Date, and SimpleDateFormat. These classes were supplanted years ago by the java.time classes.
Do not track days as a count of seconds or milliseconds. Days are not always 24 hours long, and years are not always 365 days long.
LocalDate
Instead, use LocalDate class.
LocalDate today = LocalDate.now() ;
LocalDate later = today.plusDays( 5 ) ;
Convert
Best to avoid the legacy classes altogether. But if you must interoperate with old code not yet updated to java.time classes, you can convert back-and-forth. Call new methods added to the old classes.
For Date you need to add a time-of-day. I expect you will want to go with the first moment of the day. And I'll assume you want to frame the date as UTC rather than a time zone. We must go through a OffsetDateTime object to add the time-of-day and offset. For the offset, we use the constant ZoneOffset.UTC. Then we extract the more basic Instant class object to convert to a java.util.Date.
OffsetDateTime odt = OffsetDateTime.of( later , LocalTime.MIN , ZoneOffset.UTC ) ; // Combine the date with time-of-day and with an offset-from-UTC.
Instant instant = odt.toInstant() ; // Convert to the more basic `Instant` class, a moment in UTC, always UTC by definition.
java.util.Date d = java.util.Date.from( instant ) ; // Convert from modern class to legacy class.
Going the other direction:
Instant instant = d.toInstant() ; // Convert from legacy class to modern class.
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.
Use days*86400000L to make this a long calculation otherwise the int value overflows.
Try this one in your code:
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, 5);
strDate = formatter.format(cal.getTime());
This question already has answers here:
Adding n hours to a date in Java?
(16 answers)
Closed 4 years ago.
How do i add hours to a date object. Below is my code:
String dateStart = timeStamp;
String dateStop = valueCon;
SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
d1 = format.parse(dateStart);
d2 = format.parse(datestop);
I want to add 4 hours to d2 date object. How do i achieve it?
I tried to use :
Date modd1= new Date(d2+TimeUnit.MINUTES.toHours(240));
But it accepts only long object for adding. Thus failed.
Please support to solve this.Thanks in advance.
like others, i'd recommend using java.time if that's an option. the APIs are more consistent, and do a better job of catering to these types of operations.
however, to answer your question as-is... one option is to adjust the millisecond form of the Date instance by using get/setTime() as follows:
#Test
public void adjustTime() {
final Date date = new Date();
System.out.println("## Before adding four hours: " + date);
date.setTime(date.getTime() + TimeUnit.HOURS.toMillis(4));
System.out.println("## After adding four hours: " + date);
}
hope that helps!
If you are using java.time it can be more helpful :
LocalDateTime dateStart = LocalDateTime.now();
LocalDateTime dateStop = dateStart.plusHours(4);
To format the date you can use :
String d1 = dateStart.format(DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss"));
String d2 = dateStop.format(DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss"));
Well there are several ways to do
Using Calendar class
Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(anyDateObject); // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, 4); // adds four hour
Date date = cal.getTime(); // returns new date object
If you are using ApacheCOmmon Lang
Date newDate = DateUtils.addHours(oldDate, 3);
If you are using Joda-time
DateTime dt = new DateTime();
DateTime added = dt.plusHours(4);
and if you are using Java 8 best would be LocalDateTime
LocalDateTime startDate = LocalDateTime.now();
LocalDateTime stopdate = startDate.plusHours(4);
tl;dr
Never use Date or SimpleDateFormat classes.
Use only modern java.time classes.
Example code:
LocalDateTime.parse( // Parsing input string to an object without concept of zone or offset.
"18/01/23 12:34:56" , // Input lacking indicator of zone/offset.
DateTimeFormatter.ofPattern( "uu/MM/dd HH:mm:ss" ) // Define formatting pattern matching your input.
)
.plusHours( 4 ) // Add four hours. Generating a new `LocalDateTime` object, per immutable objects pattern.
.toString() // Generate a String in standard ISO 8601 format.
2018-01-23T16:34:56
java.time
The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes. Never use Date, Calendar, SimpleDateFormat.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uu/MM/dd HH:mm:ss" ) ;
Unzoned
Apparently your input lacks an indicator of time zone or offset-from-UTC. So parse as a LocalDateTime.
LocalDateTime ldt = LocalDateTime.parse( "18/01/23 12:34:56" ) ;
ldt.toString(): 2018-01-23T12:34:56
A LocalDateTime has no concept of time zone or offset-from-UTC. So it does not represent an actual moment, and is not a point on the timeline. A LocalDateTime is only a rough idea about potential moments along a range of about 26-27 hours.
Zoned
If you know for certain the input data was intended to represent a moment in a particular zone, apply a ZoneId to produce a ZonedDateTime. A ZonedDateTime does represent an actual moment, a point on the timeline.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ; // Determining an actual moment.
zdt.toString(): 2018-01-23T12:34:56+01:00[Africa/Tunis]
To see the same moment in UTC, extract an Instant.
Instant instant = zdt.toInstant() ;
Math
Represent a span of time unattached to the timeline as a Duration object.
Duration d = Duration.ofHours( 4 ) ; // Four hours, as an object.
Add to your LocalDateTime, if not using time zones.
LocalDateTime ldtLater = ldt.plus( d ) ;
If using zoned values, add to your ZonedDateTime.
ZonedDateTime zdtLater = zdt.plus( d ) ;
Those classes also offer shortcut methods, if you wish.
ZonedDateTime zdtLater = zdt.plusHours( 4 ) ; // Alternative to using `Duration` object.
One benefit of using a Duration rather than the shortcut methods is having an object that can be named.
Duration halfShiftLater = Duration.ofHours( 4 ) ;
…
ZonedDateTime zdtLater = zdt.plus( halfShiftLater ) ;
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.
you can do something like
Calendar c = Calendar.getInstance();
c.setTimeInMillis(d2.getTime());
c.add(Calendar.HOUR_OF_DAY, 4);
d2 = c.getTime();
I recommend you using JDK8 time API or joda-time if you can.
Old java api for date is so bad!
In your case, you can:
//commons-lang3
Date oldDate = new Date();
Date newDate = DateUtils.addHours(oldDate, 1);
OR
convert date to timestamp, add some mills and convert timestamp back to date
How to extract Day, Month and Year values from a string [like 18/08/2012]. I tried using SimpleDateFormat, but it returns a Date object and I observed that all the Get methods are deprecated. Is there any better way to do this?
Thanks
Personally I'd use Joda Time, which makes life considerably simpler. In particular, it means you don't need to worry about the time zone of the Calendar vs the time zone of a SimpleDateFormat - you can just parse to a LocalDate, which is what the data really shows you. It also means you don't need to worry about months being 0-based :)
Joda Time makes many date/time operations much more pleasant.
import java.util.*;
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) throws Exception {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy")
.withLocale(Locale.UK);
LocalDate date = formatter.parseLocalDate("18/08/2012");
System.out.println(date.getYear()); // 2012
System.out.println(date.getMonthOfYear()); // 8
System.out.println(date.getDayOfMonth()); // 18
}
}
Simply go for String.split(),
String str[] = "18/08/2012".split("/");
int day = Integer.parseInt(str[0]);
int month = Integer.parseInt(str[1]);
..... and so on
This should get you going without adding external jars
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date parse = sdf.parse("18/08/2012");
Calendar c = Calendar.getInstance();
c.setTime(parse);
System.out.println(c.get(Calendar.MONTH) + c.get(Calendar.DATE) + c.get(Calendar.YEAR));
Create a java.util.Calendar object out of that date as follows and extract the date parts:
Calendar cal = Calendar.getInstance();
cal.setTime(<date from simple-date-format).
cal.get(Calendar.MONTH);
etc.,
tl;dr
java.time.LocalDate.parse(
"18/08/2012" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
).getDayOfMonth() // .getYear() .getMonth()
java.time
The modern approach uses the java.time classes. Avoid the troublesome legacy classes such as Date & Calendar.
LocalDate
String input = "18/08/2012" ;
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
ld.toString(): 2012-08-18
Getter methods
Interrogate for the parts.
int d = ld.getDayOfMonth() ;
int m = ld.getMonthValue() ;
int y = ld.getYear() ;
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.
Another approach may be use Calendar object get(Calendar.MONT)
Example:
Calendar cal = Calendar.getInstance();
cal.setTime(dateObj).
cal.get(Calendar.MONTH);
(or)
You may use String.split() also.
Use This And Pass the date Value
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
Date parse = sdf.parse("18/01/2018");
Calendar calendar = Calendar.getInstance();
calendar.setTime(parse);
int date = calendar.get(Calendar.DATE);
//+1 Is Important Because if the month is January then coming 0 so Add +1
int month = calendar.get(Calendar.MONTH)+1;
int year = calendar.get(Calendar.YEAR);
System.out.println("Date:"+date +":Month:"+ month + ":Year:"+year);
In it the String is stored in an array in form of elements, and with the help of split() function, I have separated it and retrieved it from the array str[] and stored in 3 different variables day, month & year.
import java.util.*;
public class date {
public static void main(String[] args) throws Exception {
String str[] = "18/08/2012".split("/");
int day = Integer.parseInt(str[0]);
int month = Integer.parseInt(str[1]);
int year = Integer.parseInt(str[2]);
System.out.println(day);
System.out.println(month);
System.out.println(year);
}
}