【问题标题】:how to get month name using current date as input in function如何使用当前日期作为函数的输入来获取月份名称
【发布时间】:2013-09-14 20:26:59
【问题描述】:

如何创建一个获取当前日期并返回月份名称的函数?
我只有日期而不是当前日期,它可以是任何日期,例如 2013/4/12 或 23/8/8。

点赞String monthName("2013/9/11");
调用此函数时返回月份名称。

【问题讨论】:

    标签: java android date


    【解决方案1】:

    这应该没问题。

    这取决于日期的格式。 如果您尝试使用 2011 年 2 月 1 日 它会起作用,只需根据您的需要更改此字符串“MMMM d, yyyy”。 检查this 了解所有格式模式。

    而且,月份是从 0 开始的,所以如果你希望一月是 1,只需返回月份 + 1

       private static int getMonth(String date) throws ParseException{  
                Date d = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(date);
                Calendar cal = Calendar.getInstance();
                cal.setTime(d);
                int month = cal.get(Calendar.MONTH);
                return month + 1;
        }
    

    如果你想要月份名称试试这个

    private static String getMonth(String date) throws ParseException{  
        Date d = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(date);
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        String monthName = new SimpleDateFormat("MMMM").format(cal.getTime());
        return monthName;
    }
    

    正如我所说,检查我发布的所有格式模式的网页。如果您只想要月份的 3 个字符,请使用“MMM”而不是“MMMM”

    【讨论】:

    • 它也会显示错误我把日期 2013/08/14 这个格式“yyyy/MM/dd”函数返回给我 7
    • 因为它是 0 基数。如果希望它返回 8,请将最后一行代码替换为返回月份 + 1;
    • 如何显示月份名称??它只保留号码:(
    • int 月份 = cal.get(Calendar.MONTH+1);它将返回 33
    • @user2762662 你明白了吗?
    【解决方案2】:

    java.time

    我正在贡献现代答案。

        System.out.println(LocalDate.of(2013, Month.SEPTEMBER, 11) // Define the date
                .getMonth()                                        // Get the month
                .getDisplayName(                                   // Get the month name
                        TextStyle.FULL_STANDALONE,                 // No abbreviation
                        Locale.ENGLISH));                          // In which language?
    

    输出是:

    九月

    1. 使用来自 java.time(现代 Java 日期和时间 API)中的 LocalDate 作为日期。
    2. 使用LocalDate.getMonth()Month.getDisplayName() 获取月份名称。
    3. 避免在 2013 年的旧答案中使用 DateCalendarSimpleDateFormat。这些课程设计不良、麻烦且过时。现代 API 使用起来要好得多。同时避免使用switch/case,因为月份名称已经内置,并且使用库方法可以让您的代码更清晰、更简洁且不易出错。

    使用本地日期

        LocalDate today = LocalDate.now(ZoneId.systemDefault());
        LocalDate aDate = LocalDate.of(2013, Month.SEPTEMBER, 11); // 2013/9/11
        LocalDate anotherDate = LocalDate.of(2023, 8, 8); // 23/8/8
    

    如果您将日期作为字符串输入,请使用 DateTimeFormatter 解析字符串:

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("u/M/d");
        String stringInput = "2013/4/12";
        LocalDate date = LocalDate.parse(stringInput, dateFormatter);
        System.out.println(date);
    

    2013-04-12

    使用 LocalDate.getMonth() 和 Month.getDisplayName()

    要获得月份名称,您首先需要确定月份名称的语言。我以英文为例,依旧使用之前sn-p中的date

        String monthName = date.getMonth()
                .getDisplayName(TextStyle.FULL_STANDALONE, Locale.ENGLISH);
        System.out.println(monthName);
    

    四月

    Java 知道多种语言的月份名称。如果您想要用户语言的月份名称,请将Locale.getDefault() 作为第二个参数传递给getDisplayName()

    链接

    Oracle tutorial: Date Time 解释如何使用 java.time。

    【讨论】:

      【解决方案3】:

      使用此代码 -

      Calendar calendar = new GregorianCalendar();
              calendar.setTime(date);
              int month =  calendar.get(Calendar.MONTH);
      

      所以现在您有了月份编号,您可以使用 switch case 来获取该月份的名称。

      如果您的日期是字符串格式,请使用这个-

      Date date = new SimpleDateFormat("yyyy-MM-dd").format(d)
      

      【讨论】:

      • 不是使用 12 次 swtchcase 告诉我函数使用日期返回月份名称的有效方法
      • String[] months = new String[]{"January", "February", ...}; String monthName = months[month];
      • @DiegoCNascimento 但在这种情况下绝对不需要
      • 其他方式可以是-DateFormatSymbols dfs = new DateFormatSymbols(); String[] months = dfs.getMonths();String monthName = months[month]
      • 是的,但无论如何他都应该使用资源字符串,因此在数组 (int[]) 中定位 R.string.MONTH_NAME 几乎没有内存和更漂亮的代码 IMO。两者都是可行的,请选择
      【解决方案4】:

      按名称获取当前月份的简单解决方案:

      SimpleDateFormat formatterMonth = new SimpleDateFormat("MMMM");
      String currentMonth = formatterMonth.format(new Date(System.currentTimeMillis()));
      

      使用格式 2013/9/11 按名称获取任何月份的功能:(未测试)

      private String monthName(String dateToCheck){
          Date date = new Date();
          SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
          date = formatter.parse(dateToCheck);
          SimpleDateFormat formatterMonth = new SimpleDateFormat("MMMM");
          return formatterMonth.format(new Date(date.getTime()));
      }
      

      【讨论】:

      • 我建议你不要使用SimpleDateFormatDate。这些类设计不佳且早已过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time APILocalDateDateTimeFormatter
      【解决方案5】:

      我正在使用这样的函数:

      public String getDate(String startDate) throws ParseException {
          @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          Date d = null;
          try {
              d = sdf.parse(startDate);
              sdf.applyPattern("MMMM dd, YYYY"); //this gives output as=> "Month date, year"
          } catch (Exception e) {
              Log.d("Exception", e.getLocalizedMessage());
          }
      
          return sdf.format(d);
      }
      

      【讨论】:

      • 考虑扔掉早已过时且臭名昭著的麻烦SimpleDateFormat和朋友。看看您是否可以使用desugaring 或将ThreeTenABP 添加到您的Android 项目中,以便使用现代Java 日期和时间API 的java.time。使用起来感觉好多了。
      【解决方案6】:

      您可以获得另一个答案中描述的月份的“数字”,然后您可以简单地使用开关来获取名称。 示例:

      switch(month) {
      case 0:
         your name is January
         break;
      ...
      }
      

      附:我认为月份是从零开始的,但我不是 100% 确定...

      【讨论】:

        猜你喜欢
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多