如何将日期日/月/年转换为YYYY-MM-DD HH:MM:SS的Android [重复](how

2019-09-02 04:19发布

这个问题已经在这里有一个答案:

  • 什么是解析Java中的XML日期时间的最佳方式? 9个回答

我怎么能转换成DD / MM / YYYY的日期到支持sqlite的YYYY-MM-dd'T'HH格式:MM:SS

例如:

public static String convertStringToData(String stringData)
        throws ParseException {

    SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/aaaa");//yyyy-MM-dd'T'HH:mm:ss
    SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date data = sdf.parse(stringData);
    String formattedTime = output.format(data);
    return formattedTime;
}

Answer 1:

public static String formatDate (String date, String initDateFormat, String endDateFormat) throws ParseException {

    Date initDate = new SimpleDateFormat(initDateFormat).parse(date);
    SimpleDateFormat formatter = new SimpleDateFormat(endDateFormat);
    String parsedDate = formatter.format(initDate);

    return parsedDate;
}

这将返回所解析的日期作为字符串,格式(初始和最终)作为参数传递给该方法。



Answer 2:

   SimpleDateFormat originalFormat = new SimpleDateFormat("dd MM yyyy");
   SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy MM dd HH:mm:ss" );
   Date date;
   try {
     date = originalFormat.parse("21 6 2013");
     System.out.println("Old Format :   " + originalFormat.format(date));
     System.out.println("New Format :   " + targetFormat.format(date));

    } catch (ParseException ex) {
      // Handle Exception.
    }

旧格式:21 06 2013

新格式:2013 06 21 00:00:00



Answer 3:

Date initDate = new SimpleDateFormat("dd/MM/yyyy").parse("10/12/2016");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String parsedDate = formatter.format(initDate);
System.out.println(parsedDate);


Answer 4:

public static final String DATE_DASH_FORMAT = "yyyy-MM-dd";
public static final String DATE_FORMAT = "MM/dd/yyyy"; 

public static String prepareYearMonthDateFromString( String dateStr ){
    try
    {
        Date date = new SimpleDateFormat( DATE_FORMAT , Locale.ENGLISH ).parse( dateStr );
        DateFormat formatter = new SimpleDateFormat( DATE_DASH_FORMAT , Locale.getDefault() );
        dateStr = formatter.format( date.getTime() );
    }
    catch( ParseException e )
    {
        e.printStackTrace();
    }

    return dateStr;
}


文章来源: how to convert a date dd / mm / yyyy to yyyy-MM-dd HH:mm:ss Android [duplicate]