【问题标题】:datePicker.getMonth() +1 doesn't give expected resultdatePicker.getMonth() +1 没有给出预期的结果
【发布时间】:2011-08-07 07:46:05
【问题描述】:
             Toast.makeText(getBaseContext(),
            "Date selected:" + datePicker.getMonth()+1+
            "/"+ datePicker.getDayOfMonth() +
            "/"+ datePicker.getYear() +"\n" +
            "Time Slected:" + timePicker.getCurrentHour() + 
            ":"+ timePicker.getCurrentMinute(),
            Toast.LENGTH_SHORT).show();

通过将 1 添加到 datePicker.getMonth(),我得到月份数

            output like->
            jan-01,feb-11,mar-21

但是当我删除“1”时,我会得到月份数字输出,例如

            jan-0,feb-01,mar-02

【问题讨论】:

    标签: android android-datepicker


    【解决方案1】:

    你想要括号。

    (datePicker.getMonth()+1)
    

    否则你正在做字符串连接。

    例如

    如果getMonth() 返回 0(一月),那么

    "Date selected: " + datePicker.getMonth()+1
    

    ("Date selected: " + 0) + 1
    = "Date selected: 0" + 1
    = "Date selected: 01"
    

    但是有括号

    "Date selected: " + (datePicker.getMonth()+1)
    = "Date selected: " + (0+1)
    = "Date selected: " + 1
    = "Date selected: 1"
    

    【讨论】:

      【解决方案2】:

      月份从 0 开始编入索引。因此第一个月的编号为 0,第二个月的编号为 1。

      【讨论】:

      • 正确,但不是这个问题的问题。 (由 Ray Toal 给出答案)
      • 嗯,问题是关于“获取错误的月份编号”,而不是关于“出现随机 1”。你可能是对的,答案更有帮助,但这个问题并不是那么容易理解......(即使在重新格式化之后)
      • 我起初也认为这是一个月份编号问题,基于问题 title,但 OP 已经在代码中有 + 1 所以我去了字符串连接答案。很难说,有时。 :)
      猜你喜欢
      • 2020-05-29
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-09
      • 2021-01-06
      • 2018-12-08
      相关资源
      最近更新 更多