get day month year from java.sql.date - java

My question is simple my SQL query from java returns a date and assign it to a java.sql.Date variable.
however i want to get each of the day, month and year as int. It seems that the methods getDay(),getMonth() are deprecated.
Are there any other way to achieve this?
what i tried for testing is:
String date = "2015-04-12";
java.sql.Date dat = java.sql.Date.valueOf(date);
now i want year, month and day in an int variable each.

You can do the following:
String date = "2015-04-12";
java.sql.Date dat = java.sql.Date.valueOf(date);
//create calander instance and get required params
Calendar cal = Calendar.getInstance();
cal.setTime(dat);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);

Since java.sql.Date extends java.util.Date you could use its inherited toLocalDate() method to get instance of LocalDate (available since Java 8) which supports many get...() methods like
String date = "2015-04-12";
java.sql.Date dat = java.sql.Date.valueOf(date);
LocalDate localDate = dat.toLocalDate();
System.out.println(localDate.getDayOfMonth());
System.out.println(localDate.getMonthValue());
System.out.println(localDate.getYear());
Output:
12
4
2015

Related

How to replace getDate() from the type Date which is deprecated?

I have an existing program that I have to correct . It contains these lines :
Date startDate = new Date();
int day = startDate.getDate() - 1;
but getDate() from the type Date is deprecated so i have to change it using Calender. I tried this :
Calendar startDate = Calendar.getInstance();
startDate.add(Calendar.DATE, -1);
int day= startDate.getTime();
but this results into following error :
Type mismatch: cannot convert from Date to int
One more good option is to use like :
System.out.println(DateFormat.getDateInstance().format(new Date()));
It will print the current date.
If you need time along with date then you can use like :
System.out.println(DateFormat.getDateTimeInstance().format(new Date()));
If you want to get day in month use this:
int day= startDate.get(Calendar.DAY_OF_MONTH);
If you want to get day in week use this:
int day= startDate.get(Calendar.DAY_OF_WEEK);
Also be careful about day of week, because day 0 is sunday not monday.
Field number for get and set indicating the day of the week. This
field takes values SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, and SATURDAY.
Type mismatch: cannot convert from Date to int
change
int day= startDate.getTime();
to
Date dat= startDate.getTime();//return type Date
As the javadocs suggest, use Calendar.get(Calendar.DAY_OF_MONTH)
To get the day of the month:
int day= startDate.get(Calendar.DAY_OF_MONTH);
From the Javadocs:
Field number for get and set indicating the day of the month. This is
a synonym for DATE. The first day of the month has value 1.
The getTime() function will return a Date Object which cannot be converted to int. If you want to get the day as an integer, you have to use:
int day = startDate.get(Calendar.DATE)
In Date#startDate.getDate() returns the day of the month :
Code#1-->
Date startDate = new Date();
int day = startDate.getDate() - 1;
System.out.println(day);
Through Calendar#.get(Calendar.DAY_OF_MONTH) you will get the same result as Date#startDate.getDate():
Code#2-->
Calendar startDate = Calendar.getInstance();
int day= startDate.get(Calendar.DAY_OF_MONTH)-1;
System.out.println(day);
So you can replace Code#1 by Code#2
See on java doc at http://docs.oracle.com/javase/7/docs/api/java/util/Date.html#getTime():
Date object of getTime() method return long not in int so use like:
long time = startDate.getTime();
For Calendar docs http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#getTime()
Use like below:
long time = startDate.getTime().getTime();
For day of month:
Calendar c = Calendar.getInstance();
int dayOfMonth = c.get(Calendar.DATE);
java.time
The old java.util.Date/.Calendar classes are notoriously troublesome. They have been supplanted in Java 8 and later by the new java.time framework.
Note the use of time zone. Crucial in determining a date. If omitted, you implicitly rely on the JVM’s current default time zone. Better to specify the desired/expected time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( zoneId );
int dayOfMonth = now.getDayOfMonth();
int dayOfWeek = now.getDayOfWeek().getValue();
int dayOfYear = now.getDayOfYear();
Simply type int day = startDate.get(Calendar.DAY_OF_WEEK);

get Year from java.util.Date

I have a date column in a Cassandra column family. When I retrieve data from this CF using datastax java API, this date object can be taken as a java.util.Date object.
It has a getYear() method but it is deprecated. The corresponding javadoc says:
As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.
How can I get the year, month, day attributes from this date object properly?
Could you try like tihs;
// create a calendar
Calendar cal = Calendar.getInstance();
cal.setTime(datetime); //use java.util.Date object as arguement
// get the value of all the calendar date fields.
System.out.println("Calendar's Year: " + cal.get(Calendar.YEAR));
System.out.println("Calendar's Month: " + cal.get(Calendar.MONTH));
System.out.println("Calendar's Day: " + cal.get(Calendar.DATE));
As mentioned in javadocs;
#Deprecated public int getYear() Deprecated. As of JDK version 1.1,
replaced by Calendar.get(Calendar.YEAR) - 1900. Returns a value that
is the result of subtracting 1900 from the year that contains or
begins with the instant in time represented by this Date object, as
interpreted in the local time zone. Returns: the year represented by
this date, minus 1900.
A good option is to use date format as follows:
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy");
Date date = sdf1.parse(datetime);
String year = sdf2.format(date);
use LocalDate object in java8
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
To retrieve the date & time fields you can use this code:
DateFormat.getDateTimeInstance().getCalendar().get(DateFormat.MONTH_FIELD)
Just replace MONTH_FIELD with one somehting else like "DAY_OF_WEEK_FIELD" to retrieve the day of the week (I think '1' stands for monday) or "MINUTE_FIELD" for the current minute, etc. :)

Convert integer to dates

I'm stuck at this part where I must use integer to get the individual year, month ,day, hour and min to string it into a date format, e.g. 24/01/2004 13:00.
Date Date = (years,month,day,hour,min);// error Part
System.out.println(Date);
Use Calendar#set(..)
Calendar calendar = Calendar.getInstance();
calendar.set(year,month-1,day,hour,min);//month is 0 based
Date date = calendar.getTime();
The JodaTime library is very practical to create Dates just the way you were looking for:
// omission of DateTimeZone parameter results in use of JVM default time zone
DateTime dt = new DateTime( years, month, day, hour, min, DateTimeZone.forID( "Europe/Berlin" ) );
Date date = dt.toDate();
http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html
Make use of link below to Set attributes of Date class.
Date releaseDate = new Date();
releaseDate.setYear(year);
releaseDate.setMonth(month);
......
releaseDate.setMinutes(min);
Refer Java docs Here
try this:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, day);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.YEAR, year);
.
.
.
DateFormat formatData = new SimpleDateFormat("d/M/yyyy H:mm");
System.out.println(formatData.format(cal.getTime()));
If you want to get a headstart on Java 8, you could use joda-time's LocalDateTime class, which shares quite a few method signatures with the Java 8 LocalDateTime. Though unfortunately it doesn't have LocalDateTime.of(int year, int month, int dayOfMonth, int hour, int minute) or similar methods; instead, use the constructors.

How to get last month/year in java?

How do I find out the last month and its year in Java?
e.g. If today is Oct. 10 2012, the result should be Month = 9 and Year = 2012. If today is Jan. 10 2013, the result should be Month = 12 and Year = 2012.
Your solution is here but instead of addition you need to use subtraction
c.add(Calendar.MONTH, -1);
Then you can call getter on the Calendar to acquire proper fields
int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero
int year = c.get(Calendar.YEAR);
java.time
Using java.time framework built into Java 8:
import java.time.LocalDate;
LocalDate now = LocalDate.now(); // 2015-11-24
LocalDate earlier = now.minusMonths(1); // 2015-10-24
earlier.getMonth(); // java.time.Month = OCTOBER
earlier.getMonth.getValue(); // 10
earlier.getYear(); // 2015
Use Joda Time Library. It is very easy to handle date, time, calender and locale with it and it will be integrated to java in version 8.
DateTime#minusMonths method would help you get previous month.
DateTime month = new DateTime().minusMonths (1);
you can use the Calendar class to do so:
SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
System.out.println(format.format(cal.getTime()));
This prints : 2012.09.10 11:01 for actual date 2012.10.10 11:01
The simplest & least error prone approach is... Use Calendar's roll() method. Like this:
c.roll(Calendar.MONTH, false);
the roll method takes a boolean, which basically means roll the month up(true) or down(false)?
YearMonth class
You can use the java.time.YearMonth class, and its minusMonths method.
YearMonth lastMonth = YearMonth.now().minusMonths(1);
Calling toString gives you output in standard ISO 8601 format: yyyy-mm
You can access the parts, the year and the month. You may choose to use the Month enum object, or a mere int value 1-12 for the month.
int year = lastMonth.getYear() ;
int month = lastMonth.getMonthValue() ;
Month monthEnum = lastMonth.getMonth() ;
private static String getPreviousMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
Date preMonthDate = cal.getTime();
return format.format(preMonthDate);
}
private static String getPreToPreMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH,1);
cal.add(Calendar.DATE, -1);
Date preToPreMonthDate = cal.getTime();
return format.format(preToPreMonthDate);
}
You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0
Calendar c = Calendar.getInstance();
c.set(2011, 2, 1);
c.add(Calendar.MONTH, -1);
int month = c.get(Calendar.MONTH) + 1;
assertEquals(1, month);
You get by using the LocalDate class.
For Example:
To get last month date:
LocalDate.now().minusMonths(1);
To get starting date of last month
LocalDate.now().minusMonths(1).with(TemporalAdjusters.firstDayOfMonth());
Similarly for Year:
To get last year date:
LocalDate.now().minusYears(1);
To get starting date of last year :
LocalDate.now().minusYears(1).with(TemporalAdjusters.lastDayOfYear());
Here's the code snippet.I think it works.
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleMonth=new SimpleDateFormat("MMMM YYYY");
cal.add(Calendar.MONTH, -1);
System.out.println(simpleMonth.format(prevcal.getTime()));

Adding Years to a random date from Date class

Let's say I have this:
PrintStream out = System.out;
Scanner in = new Scanner(System.in);
out.print("Enter a number ... ");
int n = in.nextInt();
I have a random date, for example, 05/06/2015 (it is not a fixed date, it is random every time). If I want to take the 'year' of the this date, and add whatever 'n' is to this year, how do i do that?
None of the methods in the Date Class are 'int'.
And to add years from an int, 'years' has to be an int as well.
You need to convert the Date to a Calendar.
Calendar c = Calendar.getInstance();
c.setTime(randomDate);
c.add(Calendar.YEAR, n);
newDate = c.getTime();
You can manipulate the Year (or other fields) as a Calendar, then convert it back to a Date.
This question has long deserved a modern answer. And even more so after Add 10 years to current date in Java 8 has been deemed a duplicate of this question.
The other answers were fine answers in 2012. The years have moved on, today I believe that no one should use the now outdated classes Calendar and Date, not to mention SimpleDateFormat. The modern Java date and time API is so much nicer to work with.
Using the example from that duplicate question, first we need
private static final DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
With this we can do:
String currentDateString = "2017-09-12 00:00:00";
LocalDateTime dateTime = LocalDateTime.parse(currentDateString, formatter);
dateTime = dateTime.plusYears(10);
String tenYearsAfterString = dateTime.format(formatter);
System.out.println(tenYearsAfterString);
This prints:
2027-09-12 00:00:00
If you don’t need the time of day, I recommend the LocalDate class instead of LocalDateTime since it is exactly a date without time of day.
LocalDate date = dateTime.toLocalDate();
date = date.plusYears(10);
The result is a date of 2027-09-12.
Question: where can I learn to use the modern API?
You may start with the Oracle tutorial. There’s much more material on the net, go search.
Another package for doing this exists in org.apache.commons.lang3.time, DateUtils.
Date date = new Date();
date = DateUtils.addYears(date, int quantity = 1);
The Date class will not help you, but the Calendar class can:
Calendar cal = Calendar.getInstance();
Date f;
...
cal.setTime(f);
cal.add(Calendar.YEAR, n); // Where n is int
f = cal.getTime();
Notice that you still have to assign a value to the f variable. I frequently use SimpleDateFormat to convert strings to dates.
Hope this helps you.
Try java.util.Calendar type.
Calendar cal=Calendar.getInstance();
cal.setTime(yourDate.getTime());
cal.set(Calendar.YEAR,n);
This will add 3 years to the current date and print the year.
System.out.println(LocalDate.now().plusYears(3).getYear());
If you need add one year a any date use the object Calendar.
Calendar dateMoreOneYear = Calendar.getInstance();
dateMoreOneYear.setTime(dateOriginal);
dateMoreOneYear.add(Calendar.DAY_OF_MONTH, 365);
Try like this as well for a just month and year like (June 2019)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, n); //here n is no.of year you want to increase
SimpleDateFormat format1 = new SimpleDateFormat("MMM YYYY");
System.out.println(cal.getTime());
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
Try this....
String s = new SimpleDateFormat("YYYY").format(new Date(random_date_in_long)); //
int i = Integer.parseInt(s)+n;

Categories

Resources