Home > Java > javaTutorial > How Can I Determine the Day of the Week for a Given Date in Java?

How Can I Determine the Day of the Week for a Given Date in Java?

DDD
Release: 2024-12-13 20:06:14
Original
757 people have browsed it

How Can I Determine the Day of the Week for a Given Date in Java?

Determining the Day of the Week from a Date

Given a specific date, determining the corresponding day of the week is a common task in programming. This question explores several approaches to retrieve the desired information.

Retrieving the Full Day of the Week

To obtain the full day of the week as a string (e.g., "Tue"), you can utilize the following methods:

  • Utilizing java.util.Calendar:
Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
Copy after login
  • Reformatting the Date String:
String dayOfWeek = new SimpleDateFormat("EE").format(date);
Copy after login

Retrieving the Day Ordinal

If you prefer to retrieve the day ordinal (e.g., 3 for Tuesday), you can employ the following technique:

int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
Copy after login

Handling Input Date Strings

In the event that your input is provided as a string rather than a Date object, you can parse it using SimpleDateFormat:

Date date = new SimpleDateFormat("dd/M/yyyy").parse(dateString);
Copy after login

Additional Libraries

  • joda-time: Using DateTime, you can call dateTime.dayOfWeek().
  • java.time (Java 8 ): Instead of joda-time, consider using the java.time package to determine day of week.

The above is the detailed content of How Can I Determine the Day of the Week for a Given Date in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template