Table of Contents
In this post, we will see how to get day from date in java.
There are multiple ways to get day from date in java. Let’s go through them.
Using java.util.Date
You can use Calendar
class to get day of week in number and SimpleDateFormat
if you need it in text format like Tuesday.
Let’s see with the help of example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package org.arpit.java2blog; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class GetDayOfWeekMain { public static void main(String[] args) { Date date=new Date(); Calendar c = Calendar.getInstance(); c.setTime(date); int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); System.out.println("Day of week in number:"+dayOfWeek); String dayWeekText = new SimpleDateFormat("EEEE").format(date); System.out.println("Day of week in text:"+dayWeekText); } } |
Output:
Day of week in text:Tuesday
Here day of week in number ranges from 1(Calendar.SUNDAY) to 7(Calendar.SATURAY). Since date of week is tuesday, that’s why we got output as 3
Using java.time.LocalDate
You can use getDayOfWeek()
method of LocalDate
class to get day name of week from date in java. It will work for Java 8 or later.
Let’s see with the help of example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package org.arpit.java2blog; import java.time.LocalDate; public class GetDayOfWeekMain { public static void main(String[] args) { LocalDate localDate = LocalDate.of(2020, 12, 22); java.time.DayOfWeek dayOfWeek = localDate.getDayOfWeek(); System.out.println("Day of week in number:"+dayOfWeek.getValue()); System.out.println("Day of week in text:"+dayOfWeek.toString()); } } |
Output:
Day of week in text:TUESDAY
Here day of week in number ranges from 1(Monday) to 7(Sunday) as it has its own enum. Since date of week is TUESDAY, that’s why we got output as 2
That’s all about How to day from date in java.