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.
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 pulling data out of an Excel sheet, to load into Hubspot, using Java.
Here is how the data looks:
this date 2018-12-31 becomes Dec 31, 2017 once it's in side Hubspot.
This is wrong!
Here is my code:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date dt = null;
try {
dt = df.parse(member.getUsageEndDate());
} catch (java.text.ParseException e3) {
//dt = null;
e3.printStackTrace();
}
Long l = dt.getTime();
If I open the data in Notepad, it looks like this: 31-May-2018
How can I get this converted properly?
tl;dr
OffsetDateTime.of(
LocalDate.parse( "2018-12-31" ) ,
LocalTime.MIN ,
ZoneOffset.UTC
)
.toInstant()
.toEpochMilli()
1546214400000
Details
Avoid legacy date-time classes
You are using troublesome old date-time classes long ago made legacy by the arrival of the java.time classes built into Java 8 and later.
ISO 8601
Your input string happens to comply with the ISO 8601 standard formats. These formats are used by default in java.time when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2018-12-31" ) ;
First moment of the day
Apparently you need the first moment of the day in UTC for that date. Use OffsetDateTime with constant ZoneOffset.UTC.
OffsetDateTime odt = OffsetDateTime.of( ld , LocalTime.MIN , ZoneOffset.UTC ) ;
Dump to console.
System.out.println( "odt.toString(): " + odt );
See this code run live at IdeOne.com.
odt.toString(): 2018-12-31T00:00Z
Count-from-epoch
You appear to want the count of milliseconds since the epoch reference date of first moment of 1970 in UTC, 1970-01-01T00:00Z. Extract an Instant object, the basic building-block class in java.time, and call its handy Instant::toEpochMilli method.
long millisecondsSinceEpoch = odt.toInstant().toEpochMilli() ;
See this code run live at IdeOne.com.
1546214400000
Going the other direction.
Instant instant = Instant.ofEpochMilli( 1_546_214_400_000L ) ;
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 a time picker in android. When the user chooses the time, it is returned two integers (hourOfDay and minute) through onTimeSet method. Its signature is shown bellow:
public void onTimeSet(TimePicker view, int hourOfDay, int minute);
What I want is to show to the user the chosen time in the local pattern. So, in Brazil or France, the time should be seen as 14:30, while in the US, 2:30 PM. At the moment I'm using joda-time library and not LocalTime, because android does not support the last one. If I can get the String pattern of time the problem is solved, because I can call the toString(String pattern) method.
LocalTime localTime = new LocalTime(hourOfDay, minute);
localTime.toString(pattern /* to be found */)
I have the same problem with another Picker. The user chooses the date and year, month and dayOfMonth are returned. In this case, in Brazil or France the date should be display as 12/01/2000 while in the US 1/12/2000.
How can I solve this? Any ideas?
Thanks in advance
The Joda-Time library is now in maintenance mode, with the team advising migration to the java.time classes.
Use the java.time framework of the ThreeTenABP library.
LocalDate ld = LocalDate.of( 2017 , 1 , 23 );
LocalTime lt = LocalTime.of( 12 , 23 ) ;
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.LONG ).withLocale( l );
String output = zdt.format( f );
Adjust to suit your taste by calling ofLocalizedDate or ofLocalizedTime, using other FormatStyle objects, other Locale objects, other zones.
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….
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;
}
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.