Android日期解析(提取月份和年份) [英] Android date parsing (Extracting month and year )

查看:1673
本文介绍了Android日期解析(提取月份和年份)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的应用程序以dd-MMM-yyyy格式解析日期。当我尝试获得月份,并获得一年的其他结果时,成功解析了该日期。我作为日期06-sep-2014但是,当我尝试从解析日期中提取月份和年份时,它显示为8个月而不是9个,而114年为零,而不是2014年。

I want my app to parse the date in format "dd-MMM-yyyy". The date has been successfully parsed when I try to get month and get year it is giving other result. I inpued 06-sep-2014 as date. But when I try to extract month and year from the parsed date it is showing 8 for month instead of 9 and 114 for year instead of 2014.

logcat输出

6

8

114

这是我的代码

    String date1 = "06 sep 2014";
    SimpleDateFormat format1 = new SimpleDateFormat("dd MMM yyyy");
    SimpleDateFormat format2 = new SimpleDateFormat("d MMM yyyy");

    Date date;

    try {
        if (date1.length() == 11) {
            date = format1.parse(date1);

        } else {
            date = format2.parse(date1);

        }
        int day=date.getDate();
        int  mon1=date.getMonth();
        int year1=date.getYear();

        System.out.println("date is:"+ date);

        System.out.println(day);
        System.out.println(mon1);
        System.out.println(year1);


    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


推荐答案

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public final class DateParseDemo {
    public static void main(String[] args){
         final DateFormat df = new SimpleDateFormat("dd MMM yyyy");
         final Calendar c = Calendar.getInstance();
         try {
             c.setTime(df.parse("06 sep 2014"));
             System.out.println("Year = " + c.get(Calendar.YEAR));
             System.out.println("Month = " + (c.get(Calendar.MONTH)));
             System.out.println("Day = " + c.get(Calendar.DAY_OF_MONTH));
         } 
         catch (ParseException e) {
             e.printStackTrace();
         }
    }
}

输出:


  • 年= 2014

  • 月= 8

  • Day = 6

而对于月份字段,这是基于0的。这意味着1月= 0和12月= 11。如javadoc所述,

And as for the month field, this is 0-based. This means that January = 0 and December = 11. As stated by the javadoc,

表示月份的get和set的字段号。这是一个特定于日历的值。今年第一个月在公历和朱利安日历是1月份是0;最后一个取决于一年中的月数。

Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

这篇关于Android日期解析(提取月份和年份)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆