I want to get the current timestamp like that : 1320917972
int time = (int) (System.currentTimeMillis());
Timestamp tsTemp = new Timestamp(t
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 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);
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());
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
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.