[java] Android Get Current timestamp?

I want to get the current timestamp like that : 1320917972

int time = (int) (System.currentTimeMillis());
Timestamp tsTemp = new Timestamp(time);
String ts =  tsTemp.toString();

This question is related to java android kotlin timestamp epoch

The answer is


You can get Current timestamp in Android by trying below code

time.setText(String.valueOf(System.currentTimeMillis()));

and timeStamp to time format

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(Long.parseLong(time.getText().toString())));
time.setText(dateString);

This code is Kotlin version. I have another idea to add a random shuffle integer in last digit for giving variance epoch time.

Kotlin version

val randomVariance = (0..100).shuffled().first()
val currentEpoch = (System.currentTimeMilis()/1000) + randomVariance

val deltaEpoch = oldEpoch - currentEpoch

I think it will be better using this kode then depend on android version 26 or more


java.time

I should like to contribute the modern answer.

    String ts = String.valueOf(Instant.now().getEpochSecond());
    System.out.println(ts);

Output when running just now:

1543320466

While division by 1000 won’t come as a surprise to many, doing your own time conversions can get hard to read pretty fast, so it’s a bad habit to get into when you can avoid it.

The Instant class that I am using is part of java.time, the modern Java date and time API. It’s built-in on new Android versions, API level 26 and up. If you are programming for older Android, you may get the backport, see below. If you don’t want to do that, understandably, I’d still use a built-in conversion:

    String ts = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
    System.out.println(ts);

This is the same as the answer by sealskej. Output is the same as before.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links


I suggest using Hits's answer, but adding a Locale format, this is how Android Developers recommends:

try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        return dateFormat.format(new Date()); // Find todays date
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }

It's simple use:

long millis = new Date().getTime();

if you want it in particular format then you need Formatter like below

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String millisInString  = dateFormat.format(new Date());

Use below method to get current time stamp. It works fine for me.

/**
 * 
 * @return yyyy-MM-dd HH:mm:ss formate date as string
 */
public static String getCurrentTimeStamp(){
    try {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentDateTime = dateFormat.format(new Date()); // Find todays date

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

        return null;
    }
}

Here's a human-readable time stamp that may be used in a file name, just in case someone needs the same thing that I needed:

package com.example.xyz;

import android.text.format.Time;

/**
 * Clock utility.
 */
public class Clock {

    /**
     * Get current time in human-readable form.
     * @return current time as a string.
     */
    public static String getNow() {
        Time now = new Time();
        now.setToNow();
        String sTime = now.format("%Y_%m_%d %T");
        return sTime;
    }
    /**
     * Get current time in human-readable form without spaces and special characters.
     * The returned value may be used to compose a file name.
     * @return current time as a string.
     */
    public static String getTimeStamp() {
        Time now = new Time();
        now.setToNow();
        String sTime = now.format("%Y_%m_%d_%H_%M_%S");
        return sTime;
    }

}

Solution in Kotlin:

val nowInEpoch = Instant.now().epochSecond

Make sure your minimum SDK version is 26.


1320917972 is Unix timestamp using number of seconds since 00:00:00 UTC on January 1, 1970. You can use TimeUnit class for unit conversion - from System.currentTimeMillis() to seconds.

String timeStamp = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));

You can use the SimpleDateFormat class:

SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String format = s.format(new Date());

From developers blog:

System.currentTimeMillis() is the standard "wall" clock (time and date) expressing milliseconds since the epoch. The wall clock can be set by the user or the phone network (see setCurrentTimeMillis(long)), so the time may jump backwards or forwards unpredictably. This clock should only be used when correspondence with real-world dates and times is important, such as in a calendar or alarm clock application. Interval or elapsed time measurements should use a different clock. If you are using System.currentTimeMillis(), consider listening to the ACTION_TIME_TICK, ACTION_TIME_CHANGED and ACTION_TIMEZONE_CHANGED Intent broadcasts to find out when the time changes.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to kotlin

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 Default interface methods are only supported starting with Android N Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6 startForeground fail after upgrade to Android 8.1 How to get current local date and time in Kotlin How to add an item to an ArrayList in Kotlin? HTTP Request in Kotlin

Examples related to timestamp

concat yesterdays date with a specific time How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Pandas: Convert Timestamp to datetime.date Spark DataFrame TimestampType - how to get Year, Month, Day values from field? What exactly does the T and Z mean in timestamp? What does this format means T00:00:00.000Z? Swift - iOS - Dates and times in different format Convert timestamp to string Timestamp with a millisecond precision: How to save them in MySQL

Examples related to epoch

How to extract epoch from LocalDate and LocalDateTime? converting epoch time with milliseconds to datetime PostgreSQL: how to convert from Unix epoch to date? How to convert a string Date to long millseconds How do I get the unix timestamp in C as an int? Convert python datetime to epoch with strftime How do I get epoch time in C#? Android Get Current timestamp? How can I convert a datetime object to milliseconds since epoch (unix time) in Python? Convert a date format in epoch