Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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?

In this example, the function should return String "Tue".

Additionally, if just the day ordinal is desired, how can that be retrieved?

1 Answer

0 votes
by (46k points)

Yes. Depending on your exact case:

  • You can use

 java.util.Calendar:Calendar c = Calendar.getInstance();

c.setTime(yourDate);

int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

  • if you need the output to be Tue rather than 3 (Days of week are indexed starting at 1), instead of going through a calendar, just reformat the string: new SimpleDateFormat("EE").format(date) (EE meaning "day of week, short version")
  • if you have your input as string, rather than Date, you should use SimpleDateFormat to parse it: new SimpleDateFormat("dd/M/yyyy").parse(dateString)
  • you can use joda-time's DateTime and call dateTime.dayOfWeek() and/or DateTimeFormat.

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...