Turning timeInMills to a 24hour/Date - java

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.

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

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.

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

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.

How to convert a date a user selects in MM-dd-yyyy format to the format yyyy-MM-dd in Java

I want to convert the incoming date from MM-dd-yyyy which is the format on the front end, and convert it to the format yyyy-MM-dd. This is useful since the backend query requires the format to be yyyy-MM-dd. I am having trouble with the syntax. I know when I do Date = new Date(), that only initializes for today's date but I want the paramater to be the incoming date that the user selects, which can be whatever it wants to be. I have two date formats set up:
public final static String getConvertedDate()
{
DateFormat userFormat = new SimpleDateFormat(MM-dd-yyyy);
DateFormat neededFormat = new SimpleDateFormat(yyyy-MM-dd);
//now I want to set it up to where I have a date the user selects
Date date = new Date() //I feel like I should input a parameter for any given date in Date() but am //unsure
//return statement returning the neededFormat
}
I may or may not be setting it up properly and am unsure if I need to set up two DateFormats like that. Any help would be much appreciated. Thanks!
You said, you want to convert a date with a given format, but you don't have a parameter for that.
public final static String getConvertedDate(String givenDaten) throws ParseException
{
DateFormat userFormat = new SimpleDateFormat(MM-dd-yyyy);
DateFormat neededFormat = new SimpleDateFormat(yyyy-MM-dd);
//first parse the userformatted date
Date userFormatDate = userFormat.parse(givenDate);
//format it as needed
return neededFormat.format(date);
}
This should do the trick:
public String convertDate(String input) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Date temp = sdf.parse(input);
sdf.applyPattern("yyyy-MM-dd");
return sdf.format(temp);
}
You should look at the format function for SimpleDateFormat
A quick example would be
public final static String getConvertedDate(String userDate)
{
DateFormat userFormat = new SimpleDateFormat(MM-dd-yyyy);
DateFormat neededFormat = new SimpleDateFormat(yyyy-MM-dd);
// Turn the String of the userDate into a date with the first format
Date formatUserDate = userFormat.parse(userDate);
// Now format that date into the correct format you want to return
return neededFormat.format(formatUserDate);
}
You need to actually parse the input String using your DateFormat:
public static void main(String[] args) throws Exception {
final DateFormat in = new SimpleDateFormat("MM-dd-yyyy");
final Date date = in.parse("03-11-2013");
System.out.println(date);
final DateFormat out = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(out.format(date));
}
Output:
Mon Mar 11 00:00:00 CET 2013
2013-03-11
Note, you're probably better off using the Date object in your code. JDBC can accept the Date with only a simple conversion to a java.sql.Date and you can convert it to any format your need later.
I would also promote the formats for class members as they are expensive to construct so should be reused, although it should be noted that they are not thread safe.
tl;dr
LocalDate.parse(
"01-23-2017" ,
DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
).toString()
2017-01-23
Using java.time
You are using troublesome old date-time classes now supplanted by java.time classes.
String input = "01-23-2017" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f );
Your desired output happens to be standard ISO 8601. The java.time classes use the standard formats by default when parsing/generating strings.
String output = ld.toString() ;
2017-01-23
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

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