264

I want to get the current timestamp like that : 1320917972

int time = (int) (System.currentTimeMillis());
Timestamp tsTemp = new Timestamp(time);
String ts =  tsTemp.toString();
Subhanshuja
  • 178
  • 1
  • 2
  • 16
Rjaibi Mejdi
  • 6,162
  • 3
  • 18
  • 26
  • 2
    FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `Timestamp` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. Most of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Nov 27 '18 at 20:31

13 Answers13

325

The solution is :

Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
Rjaibi Mejdi
  • 6,162
  • 3
  • 18
  • 26
84

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.

Trung Nguyen
  • 7,192
  • 2
  • 40
  • 82
drooooooid
  • 1,494
  • 1
  • 11
  • 16
  • 11
    From http://developer.android.com/reference/java/lang/System.html#nanoTime%28%29 I found that `System.nanoTime()` is an alternative to `System.currentTimeMillis()` and it has no unpredictable fluctuations, and is designed for measuring duration differences. – Bianca Daniciuc Sep 13 '13 at 10:49
  • 2
    @ana01 "the zero value is typically whenever the device last booted" - so it can be used only when you compare duration differences on the same device. Not useful for database storage for example. – Michał Klimczak Mar 20 '14 at 07:56
  • 1
    Just a note to @ana01 's comment that `System.nanoTime()` isn't suitable for to display wall clock time. For that purpose, use `System.currentTimeMillis()` instead. – Akash Agarwal Jan 25 '16 at 15:50
36

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()));
Hocine B
  • 374
  • 2
  • 8
sealskej
  • 7,031
  • 11
  • 49
  • 64
29

You can use the SimpleDateFormat class:

SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String format = s.format(new Date());
Pratik Butani
  • 51,868
  • 51
  • 228
  • 375
24

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;
    }
}
Hits
  • 2,780
  • 20
  • 38
13

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());
Pranav
  • 3,612
  • 2
  • 27
  • 31
8

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;
    }

}
18446744073709551615
  • 14,600
  • 3
  • 82
  • 116
  • 1
    Hey, Could u also tell the best way to sort a list of timestamps? I was thinking of sorting them myself but thought there may be a better way. – Abbas May 10 '16 at 19:57
  • For future reference for anybody reading this be aware that "android.text.format.Time" is now deprecated – jason.kaisersmith May 11 '16 at 10:50
8

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);
Mujahid Khan
  • 925
  • 1
  • 12
  • 19
4

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

Ole V.V.
  • 65,573
  • 11
  • 96
  • 117
  • 1
    Almost perfect answer (I upvoted) but, at least in my honest opinion, you should remove the ThreeTen Backport reference as this is a question about Android and not Java in general. And it may get to be confusing for beginners at Android. – Slobodan Antonijević Mar 09 '19 at 21:16
  • 1
    @SlobodanAntonijević It is important for Android programmers to understand that (a) if they are supporting Android 26 and later, they have an implementation of *java.time* built-in, (b) if supporting early Android before 26, they must add a library, the *ThreeTenABP* library, and (c) if using *ThreeTenABP*, know that this library is actually an adaptation of *ThreeTen-Backport* adapted from Java to Android. The *ThreeTenABP* library is just a Android-specific wrapper around *ThreeTen-Backport* library. See [this table graphic](https://i.stack.imgur.com/KPszD.png) comparing the 3 libraries. – Basil Bourque Sep 27 '19 at 21:01
  • @BasilBourque you are completely correct. But, you can in fact import ThreeTen-Backport and use it in an Android app, but with extremely huge impact to performance cause of its JAR dependency. This is why I've said that the post should be more specific that Android devs should never use ThreeTen-Backport, and instead use ThreeTenABP for API 25 and below support. I've seen numerous devs on various boards that get confused on which one should be used for Android, cause they sound similar by name. – Slobodan Antonijević Oct 02 '19 at 12:18
  • Good point, @SlobodanAntonijević. I have tried to make it just a little clearer. – Ole V.V. Oct 02 '19 at 12:21
  • 1
    @SlobodanAntonijević [This table](https://i.stack.imgur.com/TTAlg.png) showing where to obtain *java.time* for both Java and Android might help make it clear. – Basil Bourque Oct 02 '19 at 15:03
4

Solution in Kotlin:

val nowInEpoch = Instant.now().epochSecond

Make sure your minimum SDK version is 26.

DSavi
  • 41
  • 2
2

Here is the comparison list of the most widely known methods enter image description here

ucMedia
  • 2,500
  • 4
  • 21
  • 35
0

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;
    }
Faustino Gagneten
  • 1,968
  • 2
  • 21
  • 41
0

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

Subhanshuja
  • 178
  • 1
  • 2
  • 16