Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string Date into timestamp in Android?

I want to convert my date (which is in String format), e.g. 13-09-2011, into Timestamp. I used below code but I got the 2011-09-13 00:00:00.0 as a result. But I want Timestamp like,1312828200000 format.

I cannot understand how to convert that.

My code:

String str_date="13-09-2011"; DateFormat formatter ;  Date date ;  formatter = new SimpleDateFormat("dd-MM-yyyy"); date = (Date)formatter.parse(str_date);  java.sql.Timestamp timeStampDate = new Timestamp(date.getTime()); System.out.println("Today is " +timeStampDate); 
like image 689
krishna Avatar asked Aug 09 '11 08:08

krishna


People also ask

Is timestamp a string?

A string representation of a timestamp is a character or a Unicode graphic string that starts with a digit and has a length of at least 14 characters.

Can we convert string to timestamp in Java?

Use TimeStamp. valueOf() to Convert a String to Timestamp in Java. We will use the TimeStamp class's own static function - valueOf() . It takes a string as an argument and then converts it to a timestamp.

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.


2 Answers

If you use getTime() of Date object you will get time in millisecond. No need to use Timestamp to get your result.

String str_date="13-09-2011"; DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); Date date = (Date)formatter.parse(str_date);  System.out.println("Today is " +date.getTime()); 

The above code will print something like 1312828200000 you need and this is long value.

like image 158
Rasel Avatar answered Sep 19 '22 13:09

Rasel


String str_date=month+"-"+day+"-"+yr; DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy"); Date date = (Date)formatter.parse(str_date);  long output=date.getTime()/1000L; String str=Long.toString(output); long timestamp = Long.parseLong(str) * 1000; 
like image 27
Kishore Avatar answered Sep 19 '22 13:09

Kishore