0

I have a string that looks like "2015-06-07 16:01:33.0". I want to convert it into a unix timestamp. First I use Calendar utility to convert it into a Date object. How can I convert the date to epoch time?

String origintime = "2015-06-07 16:01:33.0";
String year = origintime.split(" ")[0].split("-")[0];            
String month = origintime.split(" ")[0].split("-")[1];
String day = origintime.split(" ")[0].split("-")[2];

String hour = origintime.split(" ")[1].split(":")[0];
String mins = origintime.split(" ")[1].split(":")[1];
String secs = origintime.split(" ")[1].split(":")[2].replace(".0","");

Calendar cal = Calendar.getInstance();    
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day));
cal.set(Calendar.MONTH, Integer.parseInt(month));
cal.set(Calendar.YEAR, Integer.parseInt(year));
cal.set(Calendar.HOUR_OF_DAY,Integer.parseInt(hour));
cal.set(Calendar.MINUTE,Integer.parseInt(mins));
cal.set(Calendar.SECOND,Integer.parseInt(secs));
String strdate = null;
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");

if (cal != null) {
    strdate = sdf.format(cal.getTime());
}
System.out.println(strdate);
Tom
  • 16,842
  • 17
  • 45
  • 54
user1189851
  • 4,861
  • 15
  • 47
  • 69
  • possible duplicate of [Getting unix timestamp from Date()](http://stackoverflow.com/questions/7784421/getting-unix-timestamp-from-date) – Stefan Jul 10 '15 at 17:39
  • 2
    Please search StackOverflow before posting. This topic has been addressed many many many times before. – Basil Bourque Jul 10 '15 at 18:28

1 Answers1

2

I think you can search for answers at StackOverflow, instead of posting a new question, since it make StackOverflow better, I just did a quick search and here they are: Getting unix timestamp from Date()

or here is the code that straight forward:

Date currentDate = new Date();
currentDate.getTime() / 1000;

Recently, people prefer jodaTime:

DateTime dateTime = new DateTime();
long unix = dateTime.getMillis()/1000; 
Community
  • 1
  • 1
super1ha1
  • 629
  • 1
  • 10
  • 17
  • 1
    Posting an Answer to a duplicate Question only encourages more duplicate Questions and contradicts your own advice in your first sentence. Instead, use the StackOverflow feature where you request this Question be closed. – Basil Bourque Jul 13 '15 at 15:49
  • thank you Basil, I did not see the closed question features ! – super1ha1 Jul 14 '15 at 02:48