Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Get Unix Time Stamp From Date

In some applications, date time is represented in Unix string format. This article explains how to use Java SimpleDateFormat and Joda libraries to get Unix time stamp from date. We create a maven based project and add the following dependency in the pom.xml file. 

 

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.6</version>
</dependency>

Write the following code in the "CurrentUnixTime.java" class.

package com.example.DataTime;

import org.joda.time.DateTime;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CurrentUnixTime {
    public static void main(String[] args)
    {
        //define simple date time format
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        //define joda date time
        DateTime dt=new DateTime();
        //get current date time
        Date currentDateTime=dt.toDate();
        //print out current date time in simple date time format
        System.out.println(currentDateTime);
        try {
            //convert current date time to unix format
            long currentDateTimeEpoch=dateFormat.parse(dateFormat.format(currentDateTime)).getTime();
            //print out unix format of current date time
            System.out.println("Current Date Time Unix Format: " +currentDateTimeEpoch);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //initialize days to add
        int daysToadd=30;
        //add days to current date
        Date newDate=dt.plusDays(daysToadd).toDate();
        //print out new date
        System.out.println("New Date after adding days "+newDate);
        try {
            //convert new date to unix string
            long newDateEpoch=dateFormat.parse(dateFormat.format(newDate)).getTime();
            //print out new date in unix format
            System.out.println("New Date Time Unix Format: " +newDateEpoch);

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

Run the code above and see the result below.

Sun May 31 22:55:07 EDT 2015
Current Date Time Unix Format: 1433127307000
New Date after adding days Tue Jun 30 22:55:07 EDT 2015
New Date Time Unix Format: 1435719307000