How to get the last week Day (saturday) Date for a particular Date. Means if I give Input as 06-04-2012
(MM-dd-YYYY)
The output should be 06-09-2012 as seen in this calendar.
Calendar cal = Calendar.getInstance();
int currentDay = cal.get(Calendar.DAY_OF_WEEK);
int leftDays= Calendar.SATURDAY - currentDay;
cal.add(Calendar.DATE, leftDays);
See
example
tl;dr
LocalDate.parse(
"06-04-2012" ,
DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
).with( TemporalAdjusters.nextOrSame( DayOfWeek.SATURDAY ) )
.format( DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) )
Using java.time
The modern way is with java.time classes.
First parse your input string as a LocalDate.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
LocalDate ld = LocalDate.parse( "06-04-2012" , f );
ld.toString(): 2012-06-04
Then get the next Saturday, or use the date itself if it is a Saturday. To specify a Saturday, use the enum DayOfWeek.SATURDAY. To find that next or same date that is a Saturday, use an implementation of TemporaAdjuster found in the TemporalAdjusters (note plural name) class.
LocalDate nextOrSameSaturday =
ld.with( TemporalAdjusters.nextOrSame( DayOfWeek.SATURDAY ) ) ;
To generate a String, I suggest calling toString to use standard ISO 8601 format.
String output = ld.toString();
2012-06-09
But if you insist, you may use the same formatter as used in parsing.
String output = ld.format( f );
06-09-2012
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 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 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.
Look at either JODA time or (if you cannot add new libraries) the Calendar class.
public Calendar lastDayOfWeek(Calendar calendar){
Calendar cal = (Calendar) calendar.clone();
int day = cal.get(Calendar.DAY_OF_YEAR);
while(cal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY){
cal.set(Calendar.DAY_OF_YEAR, ++day);
}
return cal;
}
Related
I am calling a rest web service that accepts Date. On client side, i have calling this service using JDK 8 OffsetDateTime Class.
Value that is going from my client side : 2018-07-01T05:30+05:30
Value that is accepted by Service : 2018-07-01T08:00:00.000+0000
Below is the code:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of("UTC")));
cal.set(2018, 05, 31);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.HOUR_OF_DAY, 0);
OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(cal.getTime().toInstant(), ZoneId.systemDefault());
Value of offsetDateTime that is coming with above code is 2018-07-01T05:30+05:30.
I am in IST time zone.
Can someone help as to what needs to be done to change date to 2018-07-01T08:00:00.000+0000.
tl;dr
If you want 8 AM on first day of July at UTC…
OffsetDateTime.of(
2018 , 7 , 1 , // Date (year, month 1-12 is Jan-Dec, day-of-month)
8 , 0 , 0 , 0 , // Time (hour, minute, second, nano)
ZoneOffset.UTC // Offset-from-UTC (0 = UTC)
) // Returns a `OffsetDateTime` object.
.format( // Generates a `String` object with text representing the value of the `OffsetDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSZ" , Locale.US )
) // Returns a `String` object.
2018-07-01T08:00:00.000+0000
Avoid legacy date-time classes
Never use Calendar or Date classes. They were completely supplanted by the modern java.time classes such as OffsetDateTime. You are mixing the legacy classes with the modern, and that makes no sense.
java.time
Your Question is not clear about what are your inputs and what are your outputs versus your expectations.
If you goal is 8 AM on July 1 in UTC:
LocalDate ld = LocalDate.of( 2018 , Month.JULY , 1 ) ;
LocalTime lt = LocalTime.of( 8 , 0 ) ;
OffsetDateTime odt = OffsetDateTime.of( ld , lt , ZoneOffset.UTC ) ;
odt.toString(): 2018-07-01T08:00Z
That string format complies with ISO 8061 standard. If your destination refuses that input and accepts only 2018-07-01T08:00:00.000+0000, then we must defining a formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSZ" , Locale.US );
String output = odt.format( f );
2018-07-01T08:00:00.000+0000
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
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.
i think the below code will work
public static Date ConvertToGMT() {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utc = new Date(dateFormat.format(date));
return utc;
}
You can do it like so,
offsetDateTime.atZoneSameInstant(ZoneId.of("Asia/Kolkata"))
Update
If you need an instance of OffsetDateTime here it is.
offsetDateTime.atZoneSameInstant(ZoneId.of("Asia/Kolkata")).toOffsetDateTime();
It’s not the answer you asked for, but it may be the answer you prefer in the end: Check once more whether the service you are calling accepts the format that you are already giving it. Both formats conform with ISO 8601, so it seems that the service accepts this standard format. If so, it should accept yours too.
In any case, use OffsetDateTime and the other classes from java.time exclusively and avoid the old and outdated Calendar and TimeZone classes. Basil Bourque’s answer shows the good solution.
Link: Wikipedia article: ISO 8601
I am trying to do a simple exercise where I take a date, add 90 days to it, and format it to something like this:
Monday, April 20, 1998.
I am to do this using GregorianCalendar and DateFormat. So far, I have this compiling code, but I get a runtime error where I cannot format the given Object as Date:
import java.util.*;
import java.text.*;
class Assignment21 {
public static void main(String args[]) {
GregorianCalendar ddate = new GregorianCalendar(1994, 10, 20);
ddate.add(Calendar.DAY_OF_MONTH, 90);
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MM dd, yyyy");
String date = sdf.format(ddate);
}
}
How can I correctly output the predefined GregorianCalendar date using DateFormat?
You have to correct your code:
instead of
String date = sdf.format(ddate);
try:
String date = sdf.format(ddate.getTime());
tl;dr
LocalDate.of( 1994 , Month.OCTOBER , 20 ) // Generate a date-only value, a `LocalDate` object, without time-of-day and without time zone.
.plusDays( 90 ) // Add a span of time. Using immutable objects, a new `LocalDate` object is instantiated, without altering the first.
.format(
DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
.withLocale( Locale.US )
)
Wednesday, January 18, 1995
java.time
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
LocalDate ld = LocalDate.of( 1994 , 10 , 20 ) ; // Sane numbering for year and month, unlike legacy classes. '1994' = 1994, and 10 = October.
LocalDate ldLater = ld.plusDays( 90 ) ;
Or use Month enum.
LocalDate ld = LocalDate.of( 1994 , Month.OCTOBER , 20 ) ;
LocalDate ldLater = ld.plusDays( 90 ) ;
Let java.time automatically localize for you.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ).withLocale( Locale.US ) ;
String output = ldLater.format( f ) ;
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, 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.
In Java (I'm a junior) - how do you perform various date operations?
Assess "storedDate is one week away from today" and "storedDate has passed"
I am not sure if its the best approach or how to do the condition check
java.sql.Date dueDate = (Date) loggedUser.get("dueDate");
I've seen various calculations like this - but not sure an if condition could be met like this?
Calendar c= Calendar.getInstance();
//c.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
c.set(Calendar.HOUR_OF_DAY,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
DateFormat df=new SimpleDateFormat("EEE yyyy/MM/dd HH:mm:ss");
System.out.println(df.format(c.getTime()));// This past Sunday [ May include today ]
c.add(Calendar.DATE,7);
System.out.println(df.format(c.getTime()));// Next Sunday
Step 1: Learn to read API pages.
Here is the Calendar API Page, read it.
For your class project, you don't care about timezone (since you didn't mention it in your post).
Get a date parameter: public void methodName(Date dateParameter)
Create a Calendar containing now: Calendar myCalendar = Calendar.getInstance();
Set a calendar to a date value: myCalendar.setTime(dateParameter)
"Calculate" one week from today: myCalendar.roll(Calendar.DAY_OF_YEAR, 7)
The Calendar object stores Millisecond, Second, Minute, and Hour.
Clear these using the set method.
Compare Calendar objects using the after method.
tl;dr
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) )
.with(
TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY )
)
java.time
The modern approach uses java.time classes.
Get current moment in UTC.
Instant instant = Instant.now() ;
If you care about day-of-week, you care about date. Determining a date requires a time zone. For any given moment the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same point on the timeline, different wall-clock time.
To focus on date-only without time-of-day, extract a LocalDate.
LocalDate ld = zdt.toLocalDate() ;
To adjust into other moments, use a TemporalAdjuster. Find implementations in TemporalAdjusters.
LocalDate previousOrSameSunday = ld.with(
TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY )
) ;
…and…
LocalDate nextOrSameSunday = ld.with(
TemporalAdjusters.nextOrSame( DayOfWeek.SUNDAY )
) ;
To compare, look for isBefore, isAfter, isEqual, and equals methods on the various java.time classes.
thisLocalDate.isBefore( thatLocalDate)
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.
I have created new SimpleDateFormat object which parses the given string as date object. The date format is as below:
SimpleDateFormat simpledateFormat = new SimpleDateFormat("dd-MM-yyyy");
And I am setting this date to calendar instance as below:
Date date = sampledateFormat.parse("01-08-2013");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Now I am getting the day of the day of the week from this calendar. It is giving wrong value.
System.out.println(calendar.DAY_OF_WEEK);
The output it is giving is 7 i.e. Saturday but the expected value is 5 i.e. Thursday. Whats the problem?
You should print
calendar.get(Calendar.DAY_OF_WEEK);
The Calendar class has DAY_OF_WEEK as integer constant (with value 7) which should be used in conjunction with the Calendar.get(int) method. DAY_OF_WEEK is a calendar field, and all these constant fields are used to get() different values from the calendar instance. Their value is irrelevant.
tl;dr
LocalDate.parse( // Parse the input string by specified formatting pattern to get a date-only `LocalDate` object.
"01-08-2013" ,
DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
.getDayOfWeek() // Get a `DayOfWeek` enum object. This is *not* a mere String.
.getValue() // Ask the `DayOfWeek` object for its number, 1-7 for Monday-Sunday per ISO 8601 standard.
4
java.time
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes such as SimpleDateFormat and Date and Calendar.
The LocalDate class represents a date-only value without time-of-day and without time zone.
Define a formatting pattern to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
Parse the input string.
LocalDate ld = LocalDate.parse( "01-08-2013" , f ) ;
ld.toString(): 2013-08-01
Interrogate for the day-of-week. Get a DayOfWeek enum object, one of seven pre-defined objects, for Monday-Sunday.
DayOfWeek dow = ld.getDayOfWeek() ;
dow.toString(): THURSDAY
You can ask that DayOfWeek object for a localized name and for a number 1-7 for Monday-Sunday per the ISO 8601 standard.
int dowNumber = dow.getValue() ;
4
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; // Or Locale.US, Locale.ITALY, etc.
jeudi
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, 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 try to set a simple date certain years after with calendar:
String date is a parameter of this metod.
SimpleDateFormat format = new SimpleDateFormat("dd.mm.yyyy");
String[] DateTimeParts = date.split(" ");
String dt = DateTimeParts[0];
String[] dateParts = dt.split("-");
int d = Integer.parseInt(dateParts[2]);
int y = Integer.parseInt(dateParts[0]);
int m = Integer.parseInt(dateParts[1]);
Calendar calendar = Calendar.getInstance();
calendar.set(y, m-1, d);
calendar.add(Calendar.YEAR, years);
return format.format(calendar.getTime());
}
My problem is that the date return is otherwise fine, but the month number is totally wrong, and seems to be getting bigger on each run! What I'm missing?
You are using lowercase "m" for month, when you should be using uppercase "M", i.e
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
lowercase "m" is used to format minutes - see the java API for SimpleDateFormat for more details.
You have to use uppercase for month, otherwise you get minutes =)
try:
dd.MM.yyyy
More: http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
Other Answers are correct but outdated.
tl;dr
LocalDate.parse(
"23.01.2017" ,
DateTimeFormatter.ofPattern( "dd.MM.uuuu" )
)
Avoid legacy date-time classes
FYI, 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. See Tutorial by Oracle.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM.uuuu" );
LocalDate localDate = LocalDate.parse( "23.01.2017" , f ); // January 23, 2017.
And going the other direction. Note that unlike the legacy classes, the java.time class have sane month numbering, 1-12 for January-December.
LocalDate localDate = LocalDate.of( 2017 , 1 , 23 ); January 23, 2017.
String output = localDate.format( f );
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.