【问题标题】:BlackBerry: Retrieving the current year, month, dayBlackBerry:检索当前年、月、日
【发布时间】:2012-02-04 17:09:44
【问题描述】:
//get current date
SimpleDateFormat monthFormat = new SimpleDateFormat("M");
int _currentMonth = Integer.parseInt(monthFormat.format(new Date(System.currentTimeMillis())));

SimpleDateFormat yearFormat = new SimpleDateFormat("YYYY");
int _currentYear = Integer.parseInt(yearFormat.format(new Date(System.currentTimeMillis())));

我正在尝试构建一个日历视图,并从检索当前年份和月份开始。但是,返回的是一个字符串,而我想要一个 int 在数组等中使用。

上面发布的代码给了我一个错误,很可能是由于 Integer.parseInt 函数。

我不能用吗?检索年、月和日的最佳方法是什么。

【问题讨论】:

    标签: java blackberry


    【解决方案1】:

    你可以使用calander类来获取时间

    这是默认日期,表示当前日期:

    Calendar cal=Calendar.getInstance();
            System.out.println("YEAR:"+cal.get(Calendar.YEAR)+" MONTH: "+cal.get(Calendar.MONTH)+1+"  DAY: "+cal.get(Calendar.DAY_OF_MONTH));
            //out put as YEAR:2012 MONTH: 01  DAY: 7
    

    这是指定日期:

    Date date1=new Date(Long.parseLong("13259152444455"));//or Date date1=new Date(13259152444455L);
                cal=Calendar.getInstance();
                cal.setTime(date1);
                System.out.println("YEAR:"+cal.get(Calendar.YEAR)+" MONTH: "+cal.get(Calendar.MONTH)+1+"  DAY: "+cal.get(Calendar.DAY_OF_MONTH));
        //      output as YEAR:2390 MONTH: 21  DAY: 2
    

    【讨论】:

    • 您不需要使用Long.parseLong() 将大字面量传递给Date() 构造函数。在整数文字上使用 L 后缀,例如:new Date(13259152444455L);
    【解决方案2】:
    SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
    int _currentMonth = Integer.parseInt(monthFormat.format(new Date(System.currentTimeMillis())));
    
    SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    int _currentYear = Integer.parseInt(yearFormat.format(new Date(System.currentTimeMillis())));
    

    将“M”更改为“MM”,将“YYYY”更改为“yyyy”。

    【讨论】:

      【解决方案3】:

      嗯,它确实有效!我必须使用 yyyy 而不是 YYYY。黑莓文档将其命名为 YYYY

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-23
        • 2012-05-11
        • 1970-01-01
        • 1970-01-01
        • 2011-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多