解析来自字符串的日期给出的Andr​​oid例外 [英] parse a date from string gives exception in android

查看:142
本文介绍了解析来自字符串的日期给出的Andr​​oid例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从解析字符串日期的字符串,日期格式是像周二三月19,2015 。我想分析和格式化为 YYYY-MM-DD 格式。下面code给我不同的是unparceble日期。

code:

 日期格式DF1 =新的SimpleDateFormat(YYYY-MM-DD);
尝试{
    DATE1 = df1.parse(的currentdate);
    System.out的
            .println(============我的格式化日期====================+ date1.toString());
    日历CAL = Calendar.getInstance();
    cal.setTime(DATE1);
    cal.add(Calendar.DATE,10); //添加10天    DATE1 = cal.getTime();    的System.out.println(==============添加日期==============+ date1.toString());


解决方案

我已经创建了转换日期格式的一个共同的功能。你必须通过旧日期格式,新的日期格式和日期。

 公共静态字符串convertDateFormat(字符串oldFormat,字符串newFormat,字符串inputDate)
    {
        DateFormat的theDateFormat =新的SimpleDateFormat(oldFormat);
        日期日期= NULL;        尝试
        {
            日期= theDateFormat.parse(inputDate);
        }
        赶上(ParseException的ParseException的)
        {
            //日期是无效的。做你想做的。
        }
        赶上(例外的例外)
        {
            //通用赶上。做你想做的。
        }        theDateFormat =新的SimpleDateFormat(newFormat);
        返回theDateFormat.format(日期)的ToString();
    }

//调用funcation

 字符串convertedDate = convertDateFormat(EEEE MMM DD,YYYY,YYYY-MM-DD,dateToConvert);

I want to parse a string from string to date ,Date is of format like Tuesday March 19,2015. I want to parse and format it as yyyy-dd-mm format. The below code gives me exception that "unparceble date".

Code :

DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
try {
    date1 = df1.parse(currentDate);
    System.out
            .println("============my formated date====================" + date1.toString());
    Calendar cal = Calendar.getInstance();
    cal.setTime(date1);
    cal.add(Calendar.DATE, 10); // add 10 days

    date1 = cal.getTime();

    System.out.println("==============added date==============" + date1.toString());

解决方案

I have created one common function for convert date format. You have to pass old Date format, new date format and date.

public static String convertDateFormat(String oldFormat, String newFormat, String inputDate)
    {
        DateFormat theDateFormat = new SimpleDateFormat(oldFormat);
        Date date = null;

        try
        {
            date = theDateFormat.parse(inputDate);
        }
        catch (ParseException parseException)
        {
            // Date is invalid. Do what you want.
        }
        catch (Exception exception)
        {
            // Generic catch. Do what you want.
        }

        theDateFormat = new SimpleDateFormat(newFormat);
        return theDateFormat.format(date).toString();
    }

// Call funcation

String convertedDate = convertDateFormat("EEEE MMM dd,yyyy","yyyy-MM-dd",dateToConvert);

这篇关于解析来自字符串的日期给出的Andr​​oid例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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