【问题标题】:Month name from Month Numbers in android来自Android中月份编号的月份名称
【发布时间】:2014-06-16 19:06:35
【问题描述】:

我在将月份编号转换为月份名称时遇到问题,即如果月份编号 1 或 2 仅返回 3 月。但是对于 1 它应该返回二月对吗?以前我一天有同样的问题,但第二天它自动工作了,我不知道;t 如何?但是今天再次出现这样的情况我需要一些帮助来FIX

public static String getMonthShortName(int monthNumber) {
    String monthName = "";

    if (monthNumber >= 0 && monthNumber < 12)
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.MONTH, monthNumber);

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM");
            //simpleDateFormat.setCalendar(calendar);
            monthName = simpleDateFormat.format(calendar.getTime());
        } catch (Exception e) {
            if (e != null)
                e.printStackTrace();
        }
    return monthName;
}

如果月数为 1 或 2 在此声明中

monthName = simpleDateFormat.format(calendar.getTime());

仅返回 3 月(3 月)。但对于其他数字,它工作正常。谁能帮我解决这个问题?

【问题讨论】:

标签: java android datepicker monthcalendar


【解决方案1】:

出现此问题是因为 2 月不到 30 天。

例如,今天(30.04.2014)运行这个:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 1);
System.out.println(calendar.getTime());

返回

Sun Mar 02 14:52:28 CET 2014

您应该在设置月份之前添加代码:

calendar.set(Calendar.DAY_OF_MONTH, 1);

【讨论】:

    【解决方案2】:

    以下代码用于返回正确的月份名称。

    Calendar cal=Calendar.getInstance();
    SimpleDateFormat month_date = new SimpleDateFormat("MMMM");
    int monthnum=5;
    cal.set(Calendar.MONTH,monthnum);
    String month_name = month_date.format(cal.getTime());
    
    Log.e("",""+month_name);
    

    这里的输出是 June

    【讨论】:

    • 这是正确的解决方案,我在我的应用程序中使用了类似的东西。
    • 谢谢...我的代码也一样...如果我给 5 它将正常工作 1 和 2 的问题...而且我在过去 3 个月使用我的代码它工作找。我认为这是第二次显示 1 和 2 的错误结果
    • 能否请将您的系统时间设置为 3 月 31 日,然后调用您的代码序列?你可能会有惊喜……
    【解决方案3】:

    在 Kotlin 中

    fun getMonthByNumber(monthnum:Int):String {
            val c = Calendar.getInstance()
            val month_date = SimpleDateFormat("MMMM")
            c[Calendar.MONTH] = monthnum-1
            return month_date.format(c.time)
        }
    

    谢谢

    【讨论】:

      猜你喜欢
      • 2017-02-19
      • 1970-01-01
      • 2011-03-12
      • 2019-12-26
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      相关资源
      最近更新 更多