How to determine day of week by passing specific d

2018-12-31 07:06发布

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?

标签: java date
23条回答
春风洒进眼中
2楼-- · 2018-12-31 07:34

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

查看更多
永恒的永恒
3楼-- · 2018-12-31 07:35
  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.

查看更多
余欢
4楼-- · 2018-12-31 07:35

Simply use SimpleDateFormat.

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", java.util.Locale.ENGLISH);
Date myDate = sdf.parse("28/12/2013");
sdf.applyPattern("EEE, d MMM yyyy");
String sMyDate = sdf.format(myDate);

The result is: Sat, 28 Dec 2013

The default constructor is taking "the default" Locale, so be careful using it when you need a specific pattern.

public SimpleDateFormat(String pattern) {
    this(pattern, Locale.getDefault(Locale.Category.FORMAT));
}
查看更多
谁念西风独自凉
5楼-- · 2018-12-31 07:36

One line answer:

return LocalDate.parse("06/02/2018",DateTimeFormatter.ofPattern("dd/MM/yyyy")).getDayOfWeek().name();

Usage Example:

public static String getDayOfWeek(String date){
  return LocalDate.parse(date, DateTimeFormatter.ofPattern("dd/MM/yyyy")).getDayOfWeek().name();
}

public static void callerMethod(){
   System.out.println(getDayOfWeek("06/02/2018")); //TUESDAY
}
查看更多
与君花间醉酒
6楼-- · 2018-12-31 07:37

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));
   }
}
查看更多
唯独是你
7楼-- · 2018-12-31 07:37

There is a challenge on hackerrank Java Date and Time

personally, I prefer the LocalDate class.

  1. Import java.time.LocalDate
  2. Retrieve localDate by using "of" method which takes 3 arguments in "int" format.
  3. finally, get the name of that day using "getDayOfWeek" method.

There is one video on this challenge.

Java Date and Time Hackerrank solution

I hope it will help :)

查看更多
登录 后发表回答