Java 我正在尝试将字符串日期转换为长日期

Java 我正在尝试将字符串日期转换为长日期,java,android,string,date,long-integer,Java,Android,String,Date,Long Integer,我正在将字符串日期转换为long,但我不知道如何返回long值 以及如何将字符串转换为长字符串并存储在room数据库中 package com.example.mybugetssimple; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateConverter { public static long dateCon(S

我正在将字符串日期转换为long,但我不知道如何返回long值 以及如何将字符串转换为长字符串并存储在room数据库中

package com.example.mybugetssimple;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter {

   public static long dateCon(String string_date){

        string_date = "12-December-2012";

           SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
           try {
               Date d = f.parse(string_date);
               long milliseconds = d.getTime();
               return milliseconds;
           } catch (ParseException e) {
               e.printStackTrace();
       }
       return 1;
   }
}
这样

  public static long dateCon(String string_date){
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
        Date d = null;
        try {
            d = f.parse(string_date);
            calendar.setTime(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return calendar.getTimeInMillis();

    }
试试这个

   public static String getStringDateFormTimeStamp(long timestamp) {
    try {
        Calendar calendar = Calendar.getInstance();
        TimeZone tz = TimeZone.getDefault();
        calendar.setTimeInMillis(timestamp);
        calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
        Date currenTimeZone = calendar.getTime();
        return sdf.format(currenTimeZone);
    } catch (Exception e) {
        Timber.d(e);
    }
    return "";
}


 public static long StringDateToTimeStamp(String string_date){
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy");
    Date d = null;
    try {
        d = f.parse(string_date);
        calendar.setTime(d);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return calendar.getTimeInMillis();

}

您的应用程序支持的最低API级别是哪一个?由于房间数据库不支持日期,您需要使用TypeConverter。看看这个链接,返回类型是正确的,返回类型的long是正确的,你只需要使用DAT.GETTIME,同时存储它长,同时检索你可以使用一个新的日期对象从长值。并添加到您的Android项目中,以便使用java.time,即现代java日期和时间API。使用它更好。您还可以根据问题获取字符串日期,并使方法也传递字符串日期。根据您的要求更改日期格式