Why does formatting today’s date in Android Studio give 19700101? - java

Here's my code:
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
public static void main(String[] args) {
Calendar cal = new GregorianCalendar();
Date date = new Date(System.currentTimeMillis());
cal.setTime( date );
if (Calendar.MINUTE < 40) {
if (Calendar.HOUR_OF_DAY == 0) {
cal.add(Calendar.DAY_OF_MONTH, -1);
cal.set(Calendar.HOUR_OF_DAY, 23);
}
else
cal.add(Calendar.HOUR_OF_DAY, -1);
}
int z = cal.get(Calendar.DAY_OF_MONTH);
int w = cal.get(Calendar.HOUR_OF_DAY);
SimpleDateFormat sdf_nowbasedate = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat sdf_nowbasetime = new SimpleDateFormat("HH");
String baseDate_now = sdf_nowbasedate.format(z);
String baseTime_now = sdf_nowbasetime.format(w)+ "00";
System.out.println(baseDate_now + " " + baseTime_now);
Result that I expect is "20180606 1200"(Because now time writing this article is 2018 June 6th, 1:12 PM (KST - I live in Korea)
But the result is "19700101 0900"
Why does this error happen?

int z = cal.get(Calendar.DAY_OF_MONTH);
int w = cal.get(Calendar.HOUR_OF_DAY);
SimpleDateFormat sdf_nowbasedate = new SimpleDateFormat("yyyyMMdd");
String baseDate_now = sdf_nowbasedate.format(z);
First off, this code can't even compile. There is no format function that takes an integer as a parameter. It takes a date. But assuming you're actually somehow making a date out of that number- that would make your date basically a few dozen ms off the epoch time, which is Jan 1, 1970.
Instead, pass the date in to format directly.

you must pass a Date to sdf_nowbasedate.format(Date) instead int ("z" or "w")
as you are using Calendar you must get the Date
String baseDate_now = sdf_nowbasedate.format(cal.getTime());
String baseTime_now = sdf_nowbasetime.format(cal.getTime())+ "00";

java.time
The other answers have correctly explained why your code gave you a date of January 1, 1970. I should like to contribute the modern correct version of the code. I think you’re after something like this:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMdd HHmm");
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Seoul"));
if (zdt.getMinute() < 40) {
zdt = zdt.minusHours(1);
}
ZonedDateTime wholeHours = zdt.truncatedTo(ChronoUnit.HOURS);
String baseNow = wholeHours.format(formatter);
System.out.println(baseNow);
Running this just now (00:52 in South Korea) it printed:
20180607 0000
I am using java.time, the modern Java date and time API, because Calendar, GregorianCalendar, Date and SimpleDateFormat are all long outdated and poorly designed and java.time is so much nicer to work with.
There seems to be another bug in your code. Calendar.MINUTE and Calendar.HOUR_OF_DAY are constants with values 12 and 11, so Calendar.MINUTE < 40 will always be true, and Calendar.HOUR_OF_DAY == 0 will never be. Instead you probably intended cal.get(Calendar.MINUTE) and similarly for hour of day. Lesson to learn: with the old classes it is very easy to make errors, also some that go unnoticed and others that are hard to pinpoint. I do recommend you avoid those classes.
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, I’m told) the modern API comes built-in.
In 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
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Related

Easy way to generate SimpleDateFormat

I am having this string "Mon Nov 11 10:36:53 GMT+02:00 2019". What is the pattern when using SimpleDateFormat();? Is there some way I can test or generate it without multiple try and error?
java.time and ThreeTenABP
What is the pattern when using SimpleDateFormat();?
My suggestion is that you don’t use SimpleDateFormat. That class is notoriously troublesome and long outdated. On Android — and on your API level too — you can use java.time, the modern Java date and time API.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
String stringWereHaving = "Mon Nov 11 10:36:53 GMT+02:00 2019";
ZonedDateTime dateTime = ZonedDateTime.parse(stringWereHaving, formatter);
System.out.println(dateTime);
Output is:
2019-11-11T10:36:53+02:00[Etc/GMT-2]
The only confusing thing here is that the sign used in the time zone name Etc/GMT-2 has been intentionally reversed compared to normal usage.
Only if you need an old-fashioned Date object for a legacy API not yet upgraded to java.time, convert like this:
Instant i = dateTime.toInstant();
Date oldfashionedDate = DateTimeUtils.toDate(i);
System.out.println(oldfashionedDate);
Mon Nov 11 09:36:53 CET 2019
Output comes from my computer in Europe/Copenhagen time zone, so the hour of day is adjusted by 1 hour compared to your input at offset `02:00. We have got the same point in time as in the string.
Is there some way I can test or generate it without multiple try and
error?
There’s always Java SimpleDateFormat Online Tester. I give you the link at the bottom. I don’t know of a similar service for DateTimeFormatter. Many of the patterns are the same, also the one I am using above, so it’s probably worthwhile trying.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both 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 modern 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
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Java SimpleDateFormat Online Tester
Try using
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Test{
public static void main(String[] args) {
//Try This
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss 'GMT' Z yyyy");
System.out.println(simpleDateFormat.format(new Date()));
}
}
What do you mean " Is there some way I can test or generate it without multiple try and error?"
BTW, I'm using DateFormat dateFormat = new SimpleDateFormat(<put your desired pattern here via STRING>);
and get the current date:
Date date = new Date();
String result = dateFormat.format(date); // formatting the date and passing it on string.
sample code:
DateFormat dateFormat = new SimpleDateFormat("MMM. dd, yyyy EEE HH:mm:ss");
Date date = new Date();
result = dateFormat.format(date);
Output : Nov. 13, 2019 Wed 17:02:00

How to parse two similar string to datetime in one formatter with joda?

Now I have two different formats of date written in string:
String date1 = "2018-10-12 18:01:01";// yyyy-MM-dd HH:mm:ss
String date2 = "2018-10-12 18:01";//yyyy-MM-dd HH:mm
I am using joda and I want to convert the string to DateTime,the basic way is to use two formatter to parse each of them:
DateTimeFormatter formatter1 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTimeFormatter formatter2 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
DateTime dt1 = formatter1.parseDateTime(date1);
DateTime dt2 = formatter2.parseDateTime(date2);
Above code blocks works fine but it created two formatter,since the date formate is very similar(the latter one just lack of seconds),I am wonder if there is a way that I can just use one formatter to parse all of them or I have to use two formatter?
Note:
due to the production enviroment limit,I can not use java8 now,so I want to the answer based on joda
Thanks in advance!
I just tried as below,and got IllegalArgumentException: Invalid format
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dt1 = formatter.parseDateTime(date1);
DateTime dt2 = formatter.parseDateTime(date2);
You can indicate that some parts of the format are optional using []
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm[:ss]");
LocalDateTime dateTime = LocalDateTime.parse("2018-10-12 18:01:01", formatter);
LocalDateTime dateTime1 = LocalDateTime.parse("2018-10-12 18:01", formatter);
System.out.println(dateTime + " " + dateTime1);
result is
2018-10-12T18:01:01 2018-10-12T18:01
Please see Patterns for Formatting and Parsing section for more info.
Two options:
Use java.time, the modern Java date and time API through the ThreeTen Backport library.
Use Joda-Time as you are already doing.
ThreeTen Backport
Two quotes from the Joda-Time home page:
Users are now asked to migrate to java.time (JSR-310).
Note that Joda-Time is considered to be a largely “finished” project.
No major enhancements are planned. If using Java SE 8, please migrate
to java.time (JSR-310).
The good news is you can migrate even if using Java 6 or 7. The developers of java.time (lead by Stephen Colebourne, also the lead developer of Joda-Time) have also developed the ThreeTen Backport, the backport of java.time for Java 6 and 7. See the link at the bottom.
Anton Balaniuc is already showing the code in his good answer, so there’s no use for me to repeat that here.
Joda-Time
String date1 = "2018-10-12 18:01:01";// yyyy-MM-dd HH:mm:ss
String date2 = "2018-10-12 18:01";//yyyy-MM-dd HH:mm
DateTimeFormatter parser = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd HH:mm")
.appendOptional(DateTimeFormat.forPattern(":ss").getParser())
.toFormatter();
DateTime dt1 = parser.parseDateTime(date1);
DateTime dt2 = parser.parseDateTime(date2);
System.out.println("dt1: " + dt1);
System.out.println("dt2: " + dt2);
On my computer in Europe/Copenhagen time zone the output from this snippet was:
dt1: 2018-10-12T18:01:01.000+02:00
dt2: 2018-10-12T18:01:00.000+02:00
As you can see, the key to specifying optional parts in the format is the appendOptional method of DateTimeFormatterBuilder.
Links
Joda-Time home page
Answer by Anton Balaniuc showing the code for java.time
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
You can use DateTimeFormatterBuilder class, something like this.
private DateTimeFormatter formatterBuilder() {
return new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd HH:mm")
.optionalStart().appendPattern(":ss").optionalEnd()
.toFormatter();
}

Android: How can I get the time in seconds from now until 3AM Monday next week?

I'm currently trying to create a firebase JobDispatcher within my android app that will start a job around 3am on a monday, regardless of when the job is created. I have seen examples of using Joda-Time, the Period class and TemporalAdjusters, but I am trying to support API levels 16 and up, so I need something that will work with those.
Currently I am building a new job with the following constraint (among others)
.setTrigger(Trigger.executionWindow(secondsUntilMonday,
secondsUntilMonday + toleranceInterval))
But I can't seem to find any examples of how to set my secondsUntilMonday to the number of seconds between when the method is called and around the next time 3am on a Monday rolls around.
Please help!
Here is a way that may help you:
#Test
public void computeSecondsToMonday(){
Calendar c = Calendar.getInstance();
System.out.print("\r\n" + c.getTime().toString());
long millisNow = c.getTimeInMillis();
// let's advance to nex Monday
int dw = c.get(Calendar.DAY_OF_WEEK);
// days until monday
int daysToMonday = 0;
if(dw >= Calendar.MONDAY){
daysToMonday = Calendar.SATURDAY - dw + Calendar.MONDAY;
} else {
daysToMonday = Calendar.MONDAY - dw;
}
// now add days to Monday
c.add(Calendar.DAY_OF_MONTH, daysToMonday);
c.set(Calendar.HOUR_OF_DAY, 3);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
// we're in next Monday 3:00 AM
System.out.print("\r\n" + c.getTime().toString());
// compute number of millis until Monday
long millisInMonday = c.getTimeInMillis();
long millisToMonday = millisInMonday - millisNow;
// convert millis to sec
long secondsToMonday = millisToMonday / 1000;
System.out.print(String.format("\r\nSeconds Until Monday: %d", secondsToMonday));
}
Here's an output from ExampleUnitTest in Android Studio:
Sat Oct 06 09:41:54 WEST 2018
Mon Oct 08 03:00:00 WEST 2018
Seconds Until Monday: 148686
Just adapt the method to your needs, like for example:
public long computeSecondsToMonday(){
···
return secondsToMonday;
}
Hope this is what you need.
java.time
ZoneId here = ZoneId.of("America/Danmarkshavn");
ZonedDateTime now = ZonedDateTime.now(here);
ZonedDateTime nextMondayAtThree = now.with(TemporalAdjusters.next(DayOfWeek.MONDAY))
.with(LocalTime.of(3, 0));
long secondsUntilMonday = ChronoUnit.SECONDS.between(now, nextMondayAtThree);
System.out.println(nextMondayAtThree);
System.out.println("Seconds: " + secondsUntilMonday);
When I ran this snippet just now, the output was:
2018-10-08T03:00Z[America/Danmarkshavn]
Seconds: 147419
Please substitute your time zone since it probably isn’t America/Danmarkshavn.
I also invite you to compare not just the number of lines, but in particular the ease of reading with the answer using the outdated Calendar class (don’t misunderstand me: if you wanted to use the Calendar class, that would be a good answer; I just don’t think you will want to use the Calendar class when you compare).
Question: Can I use java.time on Android API levels 16 and up?
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 new Android devices (from API level 26, I’m told) the new API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described).
On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package org.threeten.bp and subpackages.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
ThreeTen Backport project
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Java Specification Request (JSR) 310.

Turning timeInMills to a 24hour/Date

Is there any source code for turning the timeInMills to a 24hour/Date like from the messenger app. When the timeInMills is below 24 hour it will return like this 16:15 but when it is over 24hour it will return like this THU at 16:15. I am currently creating a chat app and I want to add this to my app.
Edit
Beware this line: long last24hTimestamp = current - MILLISECONDS_PER_DAY;
I'm calculating on behalf of UTC time.
To get the local time, you should take into account the timezone.
So basically you have to calculate if the timestamp timeInMillis is within the last 24h then use one format otherwise use another format.
This will help you:
public static final long MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;// In real app you should pre-calculate this value
public static final String RECENT_DATE_FORMAT = "HH:mm";
public static final String OLD_DATE_FORMAT = "E' at 'HH:mm";
public static String displayTime(long timestamp) {
long current = System.getCurrentTimeMillis();
long last24hTimestamp = current - MILLISECONDS_PER_DAY;
if (timestamp > last24hTimestamp) {
// Received message within a day, use first format
SimpleDateFormat sdf = new SimpleDateFormat(RECENT_DATE_FORMAT);
return sdf.format(new Date(timestamp));
} else {
// Message is older than 1 day. Use second format
}
}
Something you should take care of:
Consider parsing with timezone/localization if your app run in multiple places
If you're using java 8, try to use DateTimeFormatter. It's threadsafe and you can use a static instance per date format, no need to initialize SimpleDateFormat everytime you want to format a date
java.time
For work with dates or times in Java I recommend java.time, the modern Java date and time API.
static DateTimeFormatter lessThan24HoursAgoFormatter
= DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH);
static DateTimeFormatter moreThan24HoursAgoFormatter
= DateTimeFormatter.ofPattern("EEE 'at' HH:mm", Locale.ENGLISH);
static ZoneId zone = ZoneId.of("America/Yakutat");
public static String getDisplayString(long timeInMills) {
ZonedDateTime dateTime = Instant.ofEpochMilli(timeInMills)
.atZone(zone)
.truncatedTo(ChronoUnit.MINUTES);
ZonedDateTime currentTimeYesterday = ZonedDateTime.now(zone).minusDays(1);
if (dateTime.isAfter(currentTimeYesterday)) {
return dateTime.format(lessThan24HoursAgoFormatter);
} else {
return dateTime.format(moreThan24HoursAgoFormatter);
}
}
Running just now
getDisplayString(1_525_402_083_258L) returned Thu at 18:48.
getDisplayString(1_525_490_972_172L) returned just 19:29.
Please put your desired time zone where I put America/Yakutat. I recommend you insert checks that the millis denote a time that is not more than a week ago and not in the future, since the returned string would be confusing in these cases.
It’s also a possibility that a library exists out there that will format a string akin to what you desire. Use your search engine.
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 new Android devices (from API level 26, I’m told) the new API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described).
On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package org.threeten.bp and subpackages.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
ThreeTen Backport project
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Java Specification Request (JSR) 310.

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();
The solution is :
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
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.
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());
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;
}
}
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());
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);
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;
}
}
Here is the comparison list of the most widely known methods
Solution in Kotlin:
val nowInEpoch = Instant.now().epochSecond
Make sure your minimum SDK version is 26.
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
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Here is another solution, this is in kotlin:
val df: DateFormat = SimpleDateFormat("yyyy.MM.dd HH:mm:ss")
val timeStamp = df.format(Calendar.getInstance().time)
Output example:
"2022.04.22 10:22:35"
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;
}
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

Categories