简体   繁体   English

如何将日期字符串转换为Java日期?

[英]How to convert Date string to java Date?

Im having difficulty converting the following date string "2014-07-10T11:31:35" to a java Date object in android. 我在将以下日期字符串"2014-07-10T11:31:35"转换为Android中的Java Date对象时遇到困难。

so Date date = new Date("2014-07-10T11:31:35"); 所以Date date = new Date("2014-07-10T11:31:35"); returns null, which causes a null reference exception 返回null,这将导致null引用异常

public class DateUtil {

    public static String FromIsoString(String datestring)
    {
        String formattedDateString = "";
        try {
            if (!datestring.isEmpty()) {

                Date date = new Date(date string);//-->>>> returns null 
                String format = "dd/MM/yyyy";
                Locale locale = Locale.ENGLISH;
                formattedDateString = FromIsoString(date, format, locale);
            }
        }
        catch(Exception ex)
        {
            Log.e(ex.getLocalizedMessage(),"FromUtcString");
        }
        return formattedDateString;
    }


    public static  String FromIsoString(Date date, String format, Locale locale){
        String dateString = null;
        try
        {

            dateString = new SimpleDateFormat(format, locale).format(date);

        }catch (Exception ex)
        {
            Log.e(ex.getLocalizedMessage(),"FromString");
        }
        return dateString;
    }
}
/**
 * Format date with specified Date format
 * @param dateString
 * @param inFormat format of input date
 * @param outFormat format of result date
 * @return dateString
 */
public static String formatDate(String dateString, String inFormat, String outFormat){
    DateFormat inFormatter = new SimpleDateFormat(inFormat);
    inFormatter.setLenient(false);
    DateFormat outFormatter = new SimpleDateFormat(outFormat);

    Date date = null;
    try {
        date = inFormatter.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
        return "";
    }

    return outFormatter.format(date);
}

and call it like formatDate("2014-07-10T11:31:35"", inFormat, outFormat) 并将其命名为formatDate("2014-07-10T11:31:35"", inFormat, outFormat)

where inFormat = "yyyy-MM-dd'T'HH:mm:ss" and outFormat = "dd/MM/yyyy" 其中, inFormat = "yyyy-MM-dd'T'HH:mm:ss"outFormat = "dd/MM/yyyy"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM