For Example I have the date: \"23/2/2010\" (23th Feb 2010). I want to pass it to a function which would return the day of week. How can I do this?
I
You can try the following code:
import java.time.*;
public class Test{
public static void main(String[] args) {
DayOfWeek dow = LocalDate.of(2010,Month.FEBRUARY,23).getDayOfWeek();
String s = String.valueOf(dow);
System.out.println(String.format("%.3s",s));
}
}
Calendar class has build-in displayName functionality:
Calendar.getInstance().getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); // Thu
Calendar.SHORT -> Thu
Calendar.LONG_FORMAT -> Thursday
Available since Java 1.6. See also Oracle documentation
Using java.time…
LocalDate.parse( // Generate `LocalDate` object from String input.
"23/2/2010" ,
DateTimeFormatter.ofPattern( "d/M/uuuu" )
)
.getDayOfWeek() // Get `DayOfWeek` enum object.
.getDisplayName( // Localize. Generate a String to represent this day-of-week.
TextStyle.SHORT_STANDALONE , // How long or abbreviated. Some languages have an alternate spelling for "standalone" use (not so in English).
Locale.US // Or Locale.CANADA_FRENCH and such. Specify a `Locale` to determine (1) human language for translation, and (2) cultural norms for abbreviation, punctuation, etc.
)
Tue
See this code run live at IdeOne.com (but only Locale.US
works there).
See my example code above, and see the correct Answer for java.time by Przemek.
if just the day ordinal is desired, how can that be retrieved?
For ordinal number, consider passing around the DayOfWeek enum object instead such as DayOfWeek.TUESDAY. Keep in mind that a DayOfWeek
is a smart object, not just a string or mere integer number. Using those enum objects makes your code more self-documenting, ensures valid values, and provides type-safety.
But if you insist, ask DayOfWeek for a number. You get 1-7 for Monday-Sunday per the ISO 8601 standard.
int ordinal = myLocalDate.getDayOfWeek().getValue() ;
UPDATE: The Joda-Time project is now in maintenance mode. The team advises migrating to the java.time classes. The java.time framework is built into Java 8 (as well as back-ported to Java 6 & 7 and further adapted to Android).
Here is example code using the Joda-Time library version 2.4, as mentioned in the accepted answer by Bozho. Joda-Time is far superior to the java.util.Date/.Calendar classes bundled with Java.
LocalDate
Joda-Time offers the LocalDate class to represent a date-only without any time-of-day or time zone. Just what this Question calls for. The old java.util.Date/.Calendar classes bundled with Java lack this concept.
Parse the string into a date value.
String input = "23/2/2010";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
LocalDate localDate = formatter.parseLocalDate( input );
Extract from the date value the day of week number and name.
int dayOfWeek = localDate.getDayOfWeek(); // Follows ISO 8601 standard, where Monday = 1, Sunday = 7.
Locale locale = Locale.US; // Locale specifies the human language to use in determining day-of-week name (Tuesday in English versus Mardi in French).
DateTimeFormatter formatterOutput = DateTimeFormat.forPattern( "E" ).withLocale( locale );
String output = formatterOutput.print( localDate ); // 'E' is code for abbreviation of day-of-week name. See Joda-Time doc.
String outputQuébécois = formatterOutput.withLocale( Locale.CANADA_FRENCH ).print( localDate );
Dump to console.
System.out.println( "input: " + input );
System.out.println( "localDate: " + localDate ); // Defaults to ISO 8601 formatted strings.
System.out.println( "dayOfWeek: " + dayOfWeek );
System.out.println( "output: " + output );
System.out.println( "outputQuébécois: " + outputQuébécois );
When run.
input: 23/2/2010
localDate: 2010-02-23
dayOfWeek: 2
output: Tue
outputQuébécois: mar.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
public class TryDateFormats {
public static void main(String[] args) throws ParseException {
String month = "08";
String day = "05";
String year = "2015";
String inputDateStr = String.format("%s/%s/%s", day, month, year);
Date inputDate = new SimpleDateFormat("dd/MM/yyyy").parse(inputDateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(inputDate);
String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();
System.out.println(dayOfWeek);
}
}
private String getDay(Date date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
//System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
return simpleDateFormat.format(date).toUpperCase();
}
private String getDay(String dateStr){
//dateStr must be in DD-MM-YYYY Formate
Date date = null;
String day=null;
try {
date = new SimpleDateFormat("DD-MM-YYYY").parse(dateStr);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
//System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
day = simpleDateFormat.format(date).toUpperCase();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return day;
}
String input_date="01/08/2012";
SimpleDateFormat format1=new SimpleDateFormat("dd/MM/yyyy");
Date dt1=format1.parse(input_date);
DateFormat format2=new SimpleDateFormat("EEEE");
String finalDay=format2.format(dt1);
Use this code for find the Day name from a input date.Simple and well tested.