简体   繁体   中英

convert date time in a specific format to timestamp android

I want to convert two dates in this form ie...18-10-2019 01:05 pm into a timestamp and then compare them. I have tried this but it's not working

public void getTimeStamp(){

  try{
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy K:mm aa");
    Date parsedDate = dateFormat.parse("10-18-2019 01:05 pm");
    Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
    Log.d("***parsedDate",parsedDate.toString());
    Log.d("***timestamp",timestamp.toString());
  } catch(Exception e) {
       e.printStackTrace();
  } 

}

Please help me

In your code, your are using "MM-dd-yyyy K:mm aa" pattern, that mean the first value is the month. But it the parse value, "18" is the month and it's not a valid month. I think you should change the pattern to "dd-MM-yyyy K:mm aa".

And it's better to use Calendar to get the timestamp:

try {
        SimpleDateFormat dateFormat = SimpleDateFormat("MM-dd-yyyy K:mm aa");
        Date parsedDate = dateFormat.parse("10-18-2019 01:05 pm");
        Calendar cal = Calendar.getInstance();
        cal.setTime(parsedDate);
        long timestamp = cal.getTimeInMillis();
    } catch (Exception: e) {
        e.printStackTrace();
    }

Try this:

public void getTimeStamp(){

    try{

         DateFormat inputFormat = new SimpleDateFormat("dd-MM-yyyy K:mm aa");
         DateFormat outputFormat = new SimpleDateFormat("MMM dd yyyy");
         Date parsedDate = inputFormat.parse("18-10-2019 01:05 pm");
         String outputDateStr = outputFormat.format(parsedDate);
         Log.d("***parsedDate",parsedDate.toString());
         Log.d("***timestamp",outputDateStr);

    } catch(Exception e) {
            e.printStackTrace();
    } 

 }
public void getTimeStamp(){

  try{
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy K:mm aa");
    Date parsedDate = dateFormat.parse("10-18-2019 01:05 pm");
    Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
    Log.d("***parsedDate",parsedDate.toString());
    Log.d("***timestamp",timestamp.toString());
  } catch(Exception e) {
       e.printStackTrace();
  } 


 Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());


Do not cast it to Timestamp take long

Long timestamp = parsedDate.getTime();

In your code simply

replace
SimpleDateFormat("MM-dd-yyyy K:mm aa")

with
SimpleDateFormat("dd-MM-yyyy K:mm aa")

then

Calendar calendar = Calendar.getInstance();
calendar.time = dateFormat.parse("10-18-2019 01:05 pm");

return calendar.getTimeInMillis();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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