How to determine day of week by passing specific date?

前端 未结 25 1846
夕颜
夕颜 2020-11-22 05:12

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

25条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 05:49

    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 for Sunday, see Calendar.SUNDAY), 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.

    • edit: since Java 8 you can now use java.time package instead of joda-time

提交回复
热议问题