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. :)
Related
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);
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
How to get month from a date in java :
DateFormat inputDF = new SimpleDateFormat("mm/dd/yy");
Date date1 = inputDF.parse("9/30/11");
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println(month+" - "+day+" - "+year);
This code return day and year but not month.
output :
0 - 30 - 2011
This is because your format is incorrect: you need "MM/dd/yy" for the month, because "mm" is for minutes:
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Date date1 = inputDF.parse("9/30/11");
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println(month+" - "+day+" - "+year);
Prints 8 - 30 - 2011 (because months are zero-based; demo)
First, you used mm in your date format, which is "minutes" according to the Javadocs. You set the minutes to 9, not the month. It looks like the month defaults to 0 (January).
Use MM (capital 'M's) to parse the month. Then, you will see 8, because in Calendar months start with 0, not 1. Add 1 to get back the desired 9.
The first month of the year in the Gregorian and Julian calendars is
JANUARY which is 0
// MM is month, mm is minutes
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
and later
int month = cal.get(Calendar.MONTH) + 1; // To shift range from 0-11 to 1-12
If you read the SimpleDateFormat javadoc, you'll notice that mm is for minutes. You need MM for month.
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Otherwise the format doesn't read a month field and assumes a value of 0.
Month format should be MM instead of mm
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Time for someone to provide the modern answer. The other answers were good answers when the question was asked in 2013 and are still correct. Today there is no reason why you should struggle with the old, outdated and simultaneously notoriously troublesome SimpleDateFormat class. java.time, the modern Java date and time API, is so much nicer to work with:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("M/d/yy");
LocalDate date1 = LocalDate.parse("9/30/11", inputFormatter);
System.out.println(date1);
This prints
2011-09-30
The LocalDate class represents a date without time-of-day, exactly what you need, it matches your requirement much more precisely than the old classes Date and Calendar.
The format pattern strings used with DateTimeFormatter resemble those from SimpleDateFormat, there are a few differences. You may use uppercase MM to require two-digit month (like 09 for September) or a single M to allow the month to be written with one or two digits. Similarly dd or d for day of month. yy denotes two-digit year and is interpreted with base 2000, that is, from 2000 to 2099 inclusive (wouldn’t work for my birthday).
Link: Oracle tutorial Trail: Date Time explaining how to use java.time.
Try like this using MM instead of mm:-
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Date date1 = inputDF.parse("9/30/11");
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println(month+" - "+day+" - "+year);
The month printed will be 8 as index starts from 0
or try with:-
int month = cal.get(Calendar.MONTH) + 1;
mmis for minutes, use MM while specifying format.
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);// returns month value index starts from 0
I have Date today=new Date(); which returns the current date.. but when i try to display date,month,year separately with the help of
DateFormat mmFormat=new SimpleDateFormat("MM");
System.out.println(mmFormat.format(today.getMonth()));
DateFormat yyFormat=new SimpleDateFormat("yyyy");
System.out.println(yyFormat.format(today.getYear()));
it prints month as 01 and year as 1970
how to resolve this.?
mmFormat.format(today.getMonth())
You're passing an integer – the month of the date – to a date format method.
The format method interprets that integer as a UNIX timestamp – a number of seconds since 1970.
You need to pass the date itself to the formatter.
Pass the entire date to SimpleDateFormat. The format string "MM" or "yyyy" will cause it to just extract the part of the date you want.
Just use the Date today as the input argument
System.out.println(mmFormat.format(today));
and
System.out.println(yyFormat.format(today));
today.getMonth() and today.getYear() returns an int which is interpreted as an UNIX timestamp . The value is 1 and 113 , which corresponds to approximately January 1, 1970, 00:00:01 GMT and January 1, 1970, 00:01:53 GMT represented by this Date object. To get the desired result , you need to pass the Date object :
System.out.println(mmFormat.format(today));
You would need to use Calendar. Have a look at the java docs.
You can do it like this -
Calendar cal = Calendar.getInstance();
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.MONTH)); // month in the Calendar class begins from 0
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(cal.get(Calendar.MINUTE));
System.out.println(cal.get(Calendar.SECOND));
This would help you to avoid creating multiple DateFormat objects. Also in case you want to use another date instead of today's date the you can just pass the date to the cal.setTime() method.
That is because all these methods are deprecated. Use
Calendar myCalendar = GregorianCalendar.getInstance();
myCalendar.get(Calendar.MONTH);
myCalendar.get(Calendar.YEAR);
myCalendar.get(Calendar.DAY_OF_MONTH);
Better in this way
Date date=new Date(); // your date
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println(year+"\n"+month);
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()));