Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find name of day by year, month and day [duplicate]

Tags:

java

If I have int year, int month, int day in Java, how to find name of day ? Is there already some functions for this ?

like image 562
Ivana Avatar asked Jul 22 '11 11:07

Ivana


People also ask

How do I populate a day name in Excel?

Format cells to show dates as the day of the week Under Category, click Custom, and in the Type box, type dddd for the full name of the day of the week (Monday, Tuesday, and so on), or ddd for the abbreviated name of the day of the week (Mon, Tue, Wed, and so on).


2 Answers

Use SimpleDateFormat with a pattern of EEEE to get the name of the day of week.

// Assuming that you already have this. int year = 2011; int month = 7; int day = 22;  // First convert to Date. This is one of the many ways. String dateString = String.format("%d-%d-%d", year, month, day); Date date = new SimpleDateFormat("yyyy-M-d").parse(dateString);  // Then get the day of week from the Date based on specific locale. String dayOfWeek = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date);  System.out.println(dayOfWeek); // Friday 

Here it is wrapped all up into a nice Java class for you.

import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*;   public class DateUtility {      public static void main(String args[]){         System.out.println(dayName("2015-03-05 00:00:00", "YYYY-MM-DD HH:MM:ss"));     }      public static String dayName(String inputDate, String format){         Date date = null;         try {             date = new SimpleDateFormat(format).parse(inputDate);         } catch (ParseException e) {             e.printStackTrace();         }         return new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date);     } } 
like image 186
BalusC Avatar answered Oct 09 '22 07:10

BalusC


You can do something like this to get the names of the days of the week for different locales.

Here's the important part:

DateFormatSymbols dfs = new DateFormatSymbols(usersLocale); String weekdays[] = dfs.getWeekdays(); 

That can be combined with this:

Calendar cal = Calendar.getInstance(); int day = cal.get(Calendar.DAY_OF_WEEK); 

To get what you're looking for:

String nameOfDay = weekdays[day]; 
like image 36
alexcoco Avatar answered Oct 09 '22 07:10

alexcoco