I can't print GregorianCalendar
package Tests;
import java.util.Date;
import java.util.GregorianCalendar;
public class Data
{
public static void main(String[] args)
{
GregorianCalendar time = new GregorianCalendar(1999, 2, 2);
System.out.println(time);
}
}
I receive this
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Belgrade",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=119,lastRule=java.util.SimpleTimeZone[id=Europe/Belgrade,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=?,YEAR=1999,MONTH=2,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=2,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_OFFSET=?]
How I can print it?
you can use this like :-
GregorianCalendar calendar = new GregorianCalendar();
Date now = calendar.getTime();
System.out.println(now);
or
Calendar cal2 = new GregorianCalendar(2010, 9, 26); // allocate with the specified date
cal2.get(Calendar.DAY_OF_WEEK); // 1 (Sunday) to 7 (Saturday)
when you call
System.out.println(time)
you've actually calling the toString() method of the Calendar instance (in this case, a GregorianCalendar one)
In order to have a properly formatted date, use SimpleDateFormat as stated in the Javadoc
https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html
java.time
The modern solution uses the LocalDate class instead. Avoid GregorianCalendar as it is now obsolete.
LocalDate ld = LocalDate.of( 1999 , Month.FEBRUARY , 2 ) ;
ld.toString(): 1999-02-02
The toString method uses the standard ISO 8601 formats. For other formats, use the DateTimeFormatter class. Search Stack Overflow for more examples and discussion, as that has beeen covered many many times.
Generally best to let DateTimeFormatter automatically localize for you.
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ).withLocale( locale ) ;
String output = ld.format( f ) ;
mardi 2 février 1999
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.
Related
I have stored the date of a specific method each time it gets executed in ab sqlite database in 3 columns (one for the day, the month and the year).
Now I want to compare it to the date of the actutal day the user uses the app. With
Date currentTime = Calendar.getInstance().getTime()
I get this date, but how am I able to compare it to the strings I get from my database? Thank you!
Using java.time
Your Question is a duplicate of many others. So briefly…
Use java.time classes rather than the troublesome old legacy date-time classes. For Android, use libraries from the ThreeTen-Backport and ThreeTenABP projects.
Get today’s date.
ZoneId z = ZoneId.of( "America/Montreal" ) )
LocalDate today = LocalDate.now( z );
Get to parts of the date.
int y = today.getYear() ;
int m = today.getMonthValue() ;
int d = today.getDayOfMonth() ;
Query the database.
myPreparedStatement.setInt( 1 , y ) ;
myPreparedStatement.setInt( 2 , m ) ;
myPreparedStatement.setInt( 3 , d ) ;
As others suggested, you should be using date-time types in your database to store date-time values rather than mere ints for the pieces.
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.
Try this:
SimpleDateFormat formattedDate = new SimpleDateFormat("dd/MM/yyyy");
String strDate= formattedDate.format(date);
It will give you your date as shown in the Template. Now simply build a String out of your SQLite data in the same way (dd/MM/yyyy) and you cam simply compare them like shown in this post: https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java
I set Japanese date using Locale (e.g. 21 11月 2016) in my android app. But, I want to send that date into "dd-MM-yyyy" (e.g. 21-11-2016) format to my APIs.
When I try to do this I get below exception :
java.lang.IllegalArgumentException: Bad class: class java.lang.String
Below is my code :
public String convertDate(String date) {
System.out.println("......ORIGINAL DATE....... " + date); // ......ORIGINAL DATE....... 21 11月 2016
String myFormat = "dd-MM-yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, new Locale(getMyLocale())); //Japanese locale is set but tried english too
System.out.println("......CONVERTED DATE....... " + sdf.format(date)); //should be 21-11-2016 but getting above error
return sdf.format(new Date(date));
}
Moreover, for US/English Locale it works fine but for Japanese I am getting this error.
You need two formatters as below
String in = "2016年11月 21日"; // really a space here?
SimpleDateFormat sdf1 = new SimpleDateFormat ("yyyy年MM月 dd日");
Date d1 = sdf1.parse(in);
SimpleDateFormat sdf2 = new SimpleDateFormat ("dd-MM-yyyy");
System.out.println(sdf2.format(d1));
java.time
You are using the troublesome old legacy date-time classes supplanted by java.time classes.
Define a DateTimeFormatter object to match the pattern of your input strings and specify a Locale for Japan. Parse input string into a LocalDate object. Call LocalDate.parse.
Define a DateTimeFormatter object to match your desired output. Call LocalDate::format to generate a string you desire.
This has been documented many times already in StackOverflow. Please search to find example code and further discussion.
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.
This question already has answers here:
How to convert java.util.Date to java.sql.Date?
(17 answers)
Closed 7 years ago.
I am trying to generate the date of today. But I always get: "1969-12-31" as the output.
here my code:
java.util.Date d1 = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(d1.getDate());
I want to add it in a sql table, what am I doing wrong?
Any suggestions?
d1.getDate() will give an int representing the current date. Eg: 23.
What you need is d1.getTime().
java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());
java.time
In Java 8 and later you should make use of the new java.time framework. These new classes supplant the old classes which have proven so troublesome.
Time Zone
Note that time zone is crucial in determining a date.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate localDate = LocalDate.now( ZoneId );
java.sql.Date d = java.sql.Date.valueOf( localDate );
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.
The getDate() function is deprecated.
Try use this:
java.util.Date d1 = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
java.util.date.getDate documentation says that method is deprecated and time that it is returning is actually a base epoch time which begins from 1970-01-01.Learn more about it on https://en.wikipedia.org/wiki/Unix_time
In order to get the actual date you need to do the following:
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
I am trying to use Java to format a time in milliseconds into a date in UTC. I have the following code:
long ms = 1427590800000;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ROOT);
cal.setTimeInMillis(ms);
Date date = cal.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
System.out.println(dateFormat.format(date)); // 2015-03-29 02:00:00
This is printing a time in BST (i.e. using the default time-zone) rather than UTC. It seems like the time-zone being set on the calendar has no bearing on the date being printed.
The actual time in UTC is shown by the following python snippet:
import datetime
ms = 1427590800000
print datetime.datetime.utcfromtimestamp(ms/1000.0) # 2015-03-29 01:00:00
Setting the default JVM time-zone to "UTC" results in the correct date being printed, but this doesn't seem like a safe solution.
java.time
The modern approach uses the industry-leading java.time classes.
Parse as an Instant, a moment in UTC with a resolution of nanoseconds.
long input = 1_427_590_800_000L ;
Instant instant = Instant.ofEpochMilli( input ) ;
ISO 8601
Generate a string in standard ISO 8601 format.
String output = instant.toString() ;
2015-03-29T01:00:00Z
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 need to set the timezone to the formatter before formatting if you want a desired timezone.
Use dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); and then call dateFormat.format(date)
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.