Java 想要将一周中的某一天作为字符串,但给出错误的一天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18882420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:52:19  来源:igfitidea点击:

Want to get day of a week as a string, But giving wrong day

javadate

提问by JhonF

I tried to get the day as a string by using the following code. But it returns wrong string. Can I fix it with this code.

我尝试使用以下代码将日期作为字符串获取。但它返回错误的字符串。我可以用这段代码修复它吗?

private String getDayOfWeek(int value){
    String day = "";
    switch(value){
    case 1:
        day="Sunday";
        break;
    case 2:
        day="Monday";
        break;
    case 3:
        day="Tuesday";
        break;
    case 4:
        day="Wednesday";
        break;
    case 5:
        day="Thursday";
        break;
    case 6:
        day="Friday";
        break;
    case 7:
        day="Saturday";
        break;
    }
    return day;

I implements it as

我将其实现为

Calendar c = Calendar.getInstance();    
String dayOfWeek = getDayOfWeek(Calendar.DAY_OF_WEEK);
System.out.println(dayOfWeek);

采纳答案by Sotirios Delimanolis

You need to use

你需要使用

String dayOfWeek = getDayOfWeek(c.get(Calendar.DAY_OF_WEEK));

What you were doing before

你之前在做什么

String dayOfWeek = getDayOfWeek(Calendar.DAY_OF_WEEK);

is calling your method with a random constant (that happens to be 7) the Calendarclass is using to represent the DAY_OF_WEEKfield in a date.

正在使用随机常量(恰好是 7)调用您的方法,Calendar该类用于表示DAY_OF_WEEK日期中的字段。

What you are actually looking for is getting the value of the day of the week in your Calendarinstance, which is what Calendar#get(int)

您实际上正在寻找的是在您的Calendar实例中获取星期几的值,这就是Calendar#get(int)

c.get(Calendar.DAY_OF_WEEK)

returns.

返回。



On a related note, try to learn and use an actual debugger as stated in the comments.

在相关说明中,尝试学习和使用评论中所述的实际调试器。

回答by Marcelo

You can use a SimpleDateFormatfor this:

您可以SimpleDateFormat为此使用 a :

SimpleDateFormat formatter = new SimpleDateFormat("EEEE");
System.out.println(formatter.format(new Date());

This will return the String representation of the current day of the week.

这将返回一周中当前日期的字符串表示形式。

回答by Brother

I think that the best way to get the day of week is with this simple snippet of code:

我认为获取星期几的最佳方法是使用以下简单的代码片段:

Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEEE");
String dayOfWeek = dateFormat.format(date);
System.out.println(dayOfWeek);

If you want to use Calendar:

如果您想使用日历:

Calendar c = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEEE");
String dayOfWeek = dateFormat.format(c.getTime());
System.out.println(dayOfWeek);

The format "EEEEE" return the day of week: Sunday, Monday .. in the language of the machine, that is better that fix in English on the code.

格式“EEEEE”以机器语言返回星期几:星期日,星期一..,在代码上用英语修复更好。

[UPDATED]

[更新]

With Java 8+ and introducing java.time package, you can achieve this with:

使用 Java 8+ 并引入 java.time 包,您可以通过以下方式实现:

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.format.TextStyle;
import java.util.Locale;

class Example {
  public static void main(String[] args) {
    final DayOfWeek dayOfWeek = LocalDateTime.now().getDayOfWeek();
    System.out.println(dayOfWeek.getDisplayName(TextStyle.FULL, Locale.US));
  }
}

In your desired Locale, also selecting TextStyle:

在您想要的语言环境中,还选择 TextStyle:

  • FULL: Friday
  • SHORT: Fri
  • NARROW: F
  • 满:周五
  • 简短内容:周五
  • 窄:F

回答by vijaya kumar

use getdisplayname method from calender object.

使用来自日历对象的 getdisplayname 方法。

Calendar currentDate=new GregorianCalendar();

String dayOfWeek = currentDate.getDisplayName( Calendar.DAY_OF_WEEK ,Calendar.LONG, Locale.getDefault());

回答by Hardik Patel

You can use below method to get Day of the Week by passing a specific date,

您可以使用以下方法通过传递特定日期来获取星期几,

Here for the set method of Calendar class, Tricky part is the index for the month parameter will starts from 0.

这里对于 Calendar 类的 set 方法,棘手的部分是月参数的索引将从 0 开始

public static String getDay(int day, int month, int year) {

        Calendar cal = Calendar.getInstance();

        if(month==1){
            cal.set(year,0,day);
        }else{
            cal.set(year,month-1,day);
        }

        int dow = cal.get(Calendar.DAY_OF_WEEK);

        switch (dow) {
        case 1:
            return "SUNDAY";
        case 2:
            return "MONDAY";
        case 3:
            return "TUESDAY";
        case 4:
            return "WEDNESDAY";
        case 5:
            return "THURSDAY";
        case 6:
            return "FRIDAY";
        case 7:
            return "SATURDAY";
        default:
            System.out.println("GO To Hell....");
        }

        return null;
    }

回答by Hardik Patel

Below is the two line of snippet using Java 1.8 Time API.

下面是使用 Java 1.8 Time API 的两行代码片段。

LocalDate localDate = LocalDate.of(Integer.valueOf(year),Integer.valueOf(month),Integer.valueOf(day));
String dayOfWeek = String.valueOf(localDate.getDayOfWeek());

回答by Kuchi

DayOfWeek::getDisplayName

DayOfWeek::getDisplayName

There is a nice way of doing this with the DateTime API since Java 8

自 Java 8 以来,使用 DateTime API 有一种很好的方法可以做到这一点

LocalDate localDate = LocalDate.parse("2018-08-29");
DayOfWeek dayOfWeek = localDate.getDayOfWeek();
String displayName = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.ENGLISH);

Now displayNameequals Wednesday.

现在displayName等于Wednesday

With DayOfWeek.of(int dayOfWeek)there is no need for a switch statement.

随着DayOfWeek.of(int dayOfWeek)没有必要switch语句。

By number

按编号

To access the DayOfWeekby number as seen in the Question, use 1-7 for Monday-Sunday, per the ISO 8601 standard.

要访问问题中所示的DayOfWeek按编号,请根据 ISO 8601 标准在周一至周日使用 1-7。

DayOfWeek.of( 1 ).getDisplayName(TextStyle.FULL, Locale.ENGLISH)

Monday

周一

By constant

按常数

Or use one of the seven named enum objects.

或者使用七个命名的枚举对象之一。

DayOfWeek.MONDAY.getDisplayName(TextStyle.FULL, Locale.ENGLISH)

Monday

周一

回答by madhairsilence

Another brute force way is

另一种蛮力方式是

List<String> days = Arrays.asList( new String[] {"sunday","monday", "tuesday", "wednesday","thursday","friday","saturday"});

And you can use it as days.get( <your input value> );

你可以将它用作days.get( <your input value> );