Java: Get month Integer from Date
java.time (Java 8)
You can also use the java.time package in Java 8 and convert your java.util.Date
object to a java.time.LocalDate
object and then just use the getMonthValue()
method.
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int month = localDate.getMonthValue();
Note that month values are here given from 1 to 12 contrary to cal.get(Calendar.MONTH)
in adarshr's answer which gives values from 0 to 11.
But as Basil Bourque said in the comments, the preferred way is to get a Month
enum object with the LocalDate::getMonth
method.
Fast way to get month number from java.util.Date
java.time
ShaharT in an answer already mentioned Java 8 as an option. Even on Android Java 7 I believe it’s worth considering using JSR-310, the modern Java date and time API also known as java.time
for your task. It came out with Java 8, but you can use it too. It is generally much nicer to work with. It includes a class YearMonth
for representing a year and a month, just what you need, and this saves you from using two functions and instantiating a Calendar
object for each of those two method calls. So I wanted to show you the correct way to make that conversion.
I am sorry that I cannot write Kotlin code. You will have to make do with Java code, and I trust you to adapt. The Java code is:
private ZoneId zone = ZoneId.of("Europe/Moscow");
private YearMonth yearMonthFromDate(Date date) {
ZonedDateTime dateTime = date.toInstant().atZone(zone);
return YearMonth.from(dateTime);
}
Please insert your desired time zone if you didn’t want Europe/Moscow.
Now you are at it, if you go down this avenue, you may also want to consider whether you want Date
objects in you app at all, or you prefer classes from JSR-310. The Date
and Calendar
classes are considered long outmoded.
Performance
On my Mac I ran 100 000 Date
objects through the above method in 37 milliseconds. It may not be the same on an average Android device, but I’m not convinced that you need to worry about how fast the conversion is. General rule of thumb is you shouldn’t worry about it until you see a problem in a realistic setting. If not sure, then test in a realistic setting at your earliest convenience.
To use on Android
To use JSR-310 on Android you will need to have the ThreeTenABP (ABP for Android backport). It is all very well and thoroughly explained in this question: How to use ThreeTenABP in Android Project.
How to extract month from a Date variable?
Calendar cal = Calendar.getInstance();
int month = cal.get(Calendar.MONTH) + 1;
month will have 1
Get the Month from a date string
- First you need to search from next index of first
/
found means you should usefirstSlash + 1
insteadfirstSlash
indate.indexOf("/", firstSlash)
. .substring()
's 2nd paramerter is exclusive, so you need to usesecondSlash
instead ofsecondSlash-1
indate.substring(firstSlash+1, secondSlash-1)
.
Your code should be like
String date = "10/10/2020";
int firstSlash = date.indexOf("/");
int secondSlash = date.indexOf("/", firstSlash + 1);
int month = Integer.parseInt (date.substring (0, firstSlash));
int day = Integer.parseInt (date.substring(firstSlash+1, secondSlash));
It's better to use LocalDate
to store date and use DateTimeFormatter
to parse the date.
Java get month string from integer
Try:
import java.text.DateFormatSymbols;
monthString = new DateFormatSymbols().getMonths()[month-1];
Alternatively, you could use SimpleDateFormat:
import java.text.SimpleDateFormat;
System.out.println(new SimpleDateFormat("MMMM").format(date));
(You'll have to put a date with your month in a Date
object to use the second option).
I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible?
Use something like:
Date date; // your date
// Choose time zone in which you want to interpret your Date
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
// etc.
Beware, months start at 0, not 1.
Edit: Since Java 8 it's better to use java.time.LocalDate rather than java.util.Calendar. See this answer for how to do it.
Convert String Date to integer and Get Month
You don't need to parse that to date to then get the number of the month, that conversion is not necessary (you could but is a waste of memory and computational time).....
use regex, split the string and parsing the 2nd element of the array will get that directly...
public static void main(String[] args) {
String date = "15-06-2016";
String[] calend = date.split("-");
int month = Integer.parseInt(calend[1]);
System.out.println("the month is " + month);
}
Get month number from month name
Use Java's Calendar class. It can parse any given string into a valid calendar instance.
Here is an example (assuming that the month is in english).
Date date = new SimpleDateFormat("MMMM", Locale.ENGLISH).parse(monthName);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
println(cal.get(Calendar.MONTH));
You can specify the language in SimpleDateFormat:
String monthName = "März"; // German for march
Date date = new SimpleDateFormat("MMMM", Locale.GERMAN).parse(monthName);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
println(cal.get(Calendar.MONTH));
By default, Java uses the user's local to parse the string.
Keep in mind that a computer starts counting at 0. So, January will be 0. If you want a human readable date, you should format the calendar instance:
SimpleDateFormat inputFormat = new SimpleDateFormat("MMMM");
Calendar cal = Calendar.getInstance();
cal.setTime(inputFormat.parse(monthName));
SimpleDateFormat outputFormat = new SimpleDateFormat("MM"); // 01-12
println(outputFormat.format(cal.getTime()));
How do find day number(integer) of last day in the current month
have specific date and i want to find last day number(integer) of month
getActualMaximum()
is what you are looking for here.
Calendar cal = Calendar.getInstance();
cal.setTime(parsedDate);
cal.getActualMaximum(Calendar.DAY_OF_MONTH);
Related Topics
Read Rsa Private Key of Format Pkcs1 in Java
Animate JPAnel (Slide In) with Timer
Maximum Size of Hashset, Vector, Linkedlist
Execute Jsp Directly from Java
Iteratively Compute the Cartesian Product of an Arbitrary Number of Sets
Swing - Thread.Sleep() Stop Jtextfield.Settext() Working
Put Byte Array to JSON and Vice Versa
How to Select an Item from a Dropdown List Using Selenium Webdriver with Java
Differencebetween Cascade & Inverse in Hibernate, What Are They Used For
Automatic Reserved Word Escaping for Hibernate Tables and Columns
Java Two Varargs in One Method
@Preupdate and @Prepersist in Hibernate/JPA (Using Session)
How to Create a Static Local Variable in Java
Initializing an Array in Java Using the 'Advanced' for Each Loop
How to Send List of Objects to View and Back to Post Method in Controller