日期转换日期是变量字符串

时间:2014-09-29 11:16:33

标签: android

我有一个变量,它以dd / MM / yyyy的格式将日期保存为String,我想将其转换为毫秒或某种格式,以便我可以计算几天。

日期字符串来自MYSQLite数据库,它使用

以字符串形式保存到数据库中
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    Date date = new Date();

我要做的是计算从数据输入到现在的日期 我查询了数据库并将日期作为变量,但它是一个字符串......

5 个答案:

答案 0 :(得分:1)

使用此代码将字符串数据转换为Date对象:

SimpleDateFormat  format = new SimpleDateFormat("dd-MM-yyyy");  
try {  
    Date date = format.parse(dtStart);  
    //calculate the difference in days here
} catch (ParseException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
}

答案 1 :(得分:1)

您可以尝试以下代码

String someDate = "29-09-2014";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse(someDate);
System.out.println(date.getTime());

答案 2 :(得分:0)

java中的DateUtils提供了一个名为getRelativeDateTimeString()的方法来执行此操作。

Formatting of DateUtils.getRelativeDateTimeString

答案 3 :(得分:0)

public static long stringToDateMillis(String date) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
    try{
        return simpleDateFormat.parse(date).getTime();
    }catch (ParseException e){
        Log.e("Util", "Cannot parse date");
    }
    return 0;
}

答案 4 :(得分:0)

Calendar calendar = Calendar.getInstance();

calendar.set(year, Month, day, 
         0, 0, 0);
 long startTime = calendar.getTimeInMillis();

这是存储在db。

中的时间
 long endtime = System.currentmilliseconds();

 long remain= endtime-starttime;

然后计算剩余天数(毫秒)。

相关问题