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
Related
I have SAS date objects stored as integer and they look like : 19725.
I am trying to write java code to convert the date to YYYY-MM-DD
I see in the documentation that the SAS date value is the number of days from 01 Jan 1960
For example:
02 Jan 1960 would return 1
04 June 2003 would return 15680
Could you give the java code for this conversion. ie. convert something like 19725 to the date format : YYYY-MM-DD
I try the logic below but 15680 gives 2003-01-06 and not 2003-06-04 as the output. Could anyone point the mistake.Thanks in advance.
int numdays = 15680;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 1960);
cal.add(Calendar.DAY_OF_MONTH, numdays);
String strdate = null;
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
if (cal != null) {
strdate = sdf.format(cal.getTime());
}
System.out.println(strdate);
Month are 0-based, so you're setting your calendar to February, not January. This should fix the issue:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, Calendar.JANUARY);
// ...
In addition to RC's point about starting the month correctly with Calendar.JANUARY, your simpledateformat is wrong.
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
'DD' is day of year (so 340th day of the year is Dec 6). 'dd' is day of the month. See the doc for more detail. (Also note that 15680 is Dec 6 2002, not what you say in the question.)
You may actually want to use 'yy' also:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
as 'YYYY' is "Week Year", which in some cases may differ from yyyy (calendar year) near the end of the year. See the docs for more details.
I like to use JodaTime for date manipulation like this.
http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#plusDays-int-
int sasDate = 19725;
DateTime base = new DateTime(1960, 1, 1, 0, 0);
DateTime computed = base.plusDays(sasDate);
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. :)
int day = Integer.parseInt(request.getParameter("day")); // 25
int month = Integer.parseInt(request.getParameter("month")); // 12
int year = Integer.parseInt(request.getParameter("year")); // 1988
System.out.println(year);
Calendar c = Calendar.getInstance();
c.set(year, month, day, 0, 0);
b.setDob(c.getTime());
System.out.println(b.getDob());
Output is:
1988
Wed Jan 25 00:00:08 IST 1989
I am passing 25 12 1988 but I get 25 Jan 1989. Why?
Months are zero-based in Calendar. So 12 is interpreted as december + 1 month. Use
c.set(year, month - 1, day, 0, 0);
That's my favorite way prior to Java 8:
Date date = new GregorianCalendar(year, month - 1, day).getTime();
I'd say this is a bit cleaner than:
calendar.set(year, month - 1, day, 0, 0);
java.time
Using java.time framework built into Java 8
int year = 2015;
int month = 12;
int day = 22;
LocalDate.of(year, month, day); //2015-12-22
LocalDate.parse("2015-12-22"); //2015-12-22
//with custom formatter
DateTimeFormatter.ofPattern formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate.parse("22-12-2015", formatter); //2015-12-22
If you need also information about time(hour,minute,second) use some conversion from LocalDate to LocalDateTime
LocalDate.parse("2015-12-22").atStartOfDay() //2015-12-22T00:00
Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.
Here is a quick example using LocalDate from the Joda Time library:
LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();
Here you can follow a quick start tutorial.
See JavaDoc:
month - the value used to set the MONTH calendar field. Month value is
0-based. e.g., 0 for January.
So, the month you set is the first month of next year.
Make your life easy when working with dates, timestamps and durations. Use HalDateTime from
http://sourceforge.net/projects/haldatetime/?source=directory
For example you can just use it to parse your input like this:
HalDateTime mydate = HalDateTime.valueOf( "25.12.1988" );
System.out.println( mydate ); // will print in ISO format: 1988-12-25
You can also specify patterns for parsing and printing.
Today is 2013-02-25, but why this code returns 2013-03-25?
String currentDate = new SimpleDateFormat("yyyy MM dd hh mm ss").format(new java.util.Date());
System.out.println("current Date "+currentDate);
StringTokenizer token = new StringTokenizer(currentDate);
Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()));
String calenderDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(cal.getTime());
System.out.println("calender date "+calenderDate);
cal.add(Calendar.MONTH, -1); // set to one month ago
String pastDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(cal.getTime());
System.out.println("past Date "+pastDate);
out put
current Date 2013 02 25 04 56 26
calender date 2013-03-25 04:56:26
past Date 2013-02-25 04:56:26
Subtract one to the month. So it works the API. I.e.:
month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
In the JDK, month values start with 0. So 2 = March.
From the Calendar#set docs:
month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
Calendar months start at 0, see JavaDoc:
#param month the value used to set the MONTH calendar field.
* Month value is 0-based. e.g., 0 for January.
This is a royal PITA and most Java developers lost some time on that one, it certainly violates the principle of least surprise. Be very careful when using the Calendar class... There are alternatives like Joda time.
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()));