This question already has answers here:
Time Difference of two different timezone
(5 answers)
Closed 1 year ago.
I want to calculate the time difference between two different timezones like country1 (GMT+05:30) and country2 (GMT+05:00). How to calculate it. Thanks in advance.
You can find it using java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenience methods were introduced.
import java.time.Duration;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(formatDuration(diffBetweenTimeZones("GMT+05:30", "GMT+05:00")));
System.out.println(formatDuration(diffBetweenTimeZones("GMT+05:00", "GMT+05:30")));
// You can use the returned value to get the ZoneOffset which you can use for
// various kinds of processing e.g.
ZoneOffset offset = ZoneOffset.of(formatDuration(diffBetweenTimeZones("GMT+05:30", "GMT+05:00")));
System.out.println(offset);
System.out.println(OffsetDateTime.now(offset));
}
static Duration diffBetweenTimeZones(String tz1, String tz2) {
LocalDate today = LocalDate.now();
return Duration.between(today.atStartOfDay(ZoneId.of(tz1)), today.atStartOfDay(ZoneId.of(tz2)));
}
static String formatDuration(Duration duration) {
long hours = duration.toHours();
long minutes = duration.toMinutes() % 60;
String symbol = hours < 0 || minutes < 0 ? "-" : "+";
return String.format(symbol + "%02d:%02d", Math.abs(hours), Math.abs(minutes));
// ####################################Java-9####################################
// return String.format(symbol + "%02d:%02d", Math.abs(duration.toHoursPart()),
// Math.abs(duration.toMinutesPart()));
// ####################################Java-9####################################
}
}
Output:
+00:30
-00:30
+00:30
2021-03-24T10:37:31.056405+00:30
Learn more about the modern date-time API from Trail: Date Time.
Note that the java.util date-time API is outdated and error-prone. It is recommended to stop using it completely and switch to the modern date-time API*.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Related
This question already has answers here:
Java DateTimeFormatter parsing with special characters
(2 answers)
Closed 1 year ago.
How can this string 20190612070000.000[-4:EDT] be parsed into ZonedDateTime?
I've tried this pattern and bunch of others, but nothing works so far:
String dateString = "20190612070000.000[-4:EDT]";
ZonedDateTime dateTime = ZonedDateTime.parse(dateString, ofPattern("yyyyMMddHHmmss.S[x:z]"));
There is no OOTB (Out-Of-The-Box) DateTimeFormatter with the pattern matching your date-time string. You can define one using DateTimeFormatterBuilder.
Demo:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendPattern("uuuuMMddHHmmss.SSS")
.appendLiteral('[')
.appendOffset("+H", "")
.appendLiteral(':')
.appendZoneText(TextStyle.SHORT)
.appendLiteral(']')
.toFormatter(Locale.ENGLISH);
String strDateTime = "20190612070000.000[-4:EDT]";
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
System.out.println(zdt);
}
}
Output:
2019-06-12T07:00-04:00[America/New_York]
Learn more about java.time, the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Trying to write a logic in Karate DSL where, I need a date in yyyy-mm-dd format. If day is Saturday then 2 day should get added to the current date, 1 day if the day Sunday. Here is something that I'm trying but it is not working.
* def logic =
"""
function() {
var date = function() {
var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
var sdf = new SimpleDateFormat('yyyy-MM-dd');
return sdf.format(new java.util.Date());
}
var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
var sdf = new SimpleDateFormat('EEEE');
var day = sdf.format(new java.util.Date());
var c = Java.type('java.util.Calendar');
if (day== 'Saturday')
return Calendar.add(date(),2);
}
"""
The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Solution using the modern API:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Current date
// Change the JVM's default ZoneId as applicable e.g. ZoneId.of("Asia/Kolkata")
LocalDate date = LocalDate.now(ZoneId.systemDefault());
if (date.getDayOfWeek() == DayOfWeek.SATURDAY)
date = date.plusDays(2);
else if (date.getDayOfWeek() == DayOfWeek.SUNDAY)
date = date.plusDays(1);
System.out.println(date);
// Print day name
System.out.println(date.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH));
}
}
Output:
2021-05-10
Monday
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
I know this should be simple, but I can't find anything on the internet.
Given some conditions, I want to get the next Date when they will be met. For example, if conditions are minute = 01 and second = 30 and now the time is 15:58:00, the function should return today at 16:01:30. How can I accomplish this in Java?
I need to be able to set conditions of, at least, seconds, minutes and hours, but I would like to have the possibility to set one condition to any value (like the example above, that doesn't specify an hour).
Thanks and sorry for my bad English.
EDIT:
I see there's something that might need clarification: I want to get a Date (or whatever) always after the current time that meets conditions. Also, this is for a Minecraft Spigot server, maybe this information can help.
You could use streams for this:
Optional<LocalDateTime> firstMatch =
Stream.iterate(
LocalDateTime.now(),
ldt -> ldt.plusSeconds(1L))
.filter(
// Insert your condition here
ldt -> ldt.getSecond() == 0)
.findFirst();
What this code does is take the current LocalDateTime and use it to generate a stream of LocalDateTime objects (advancing the time by 1 second each time). Once it encounters a LocalDateTime that matches the provided condition, it returns this objects and terminates the stream.
Keep in mind that using this approach will generate a lot of objects if it takes a while for the condition to become true, so it is not very efficient.
If you want to strip the nanoseconds replace LocalDateTime.now() by LocalDateTime.now().withNano(0).
You can use LocalDateTime#plus... to add duration to get the updated time.
Demo:
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
String strTime = "15:58:00";
LocalTime time = LocalTime.parse(strTime);
// Today at the specified time
LocalDateTime today = LocalDateTime.now().with(time);
System.out.println(today);
// Today with the added minutes and seconds
LocalDateTime updated = today.plusMinutes(1).plusSeconds(30);
System.out.println(updated);
}
}
Output:
2021-02-23T15:58
2021-02-23T15:59:30
If you want to switch to a different time, you can use LocalDateTime#with...
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
String strTime = "15:58:00";
LocalTime time = LocalTime.parse(strTime);
// Today at the specified time
LocalDateTime today = LocalDateTime.now().with(time);
System.out.println(today);
// Today with the updated minute and second
LocalDateTime updated = today.withMinute(1).withSecond(30);
System.out.println(updated);
}
}
Output:
2021-02-23T15:58
2021-02-23T15:01:30
Learn more about the modern date-time API from **[Trail: Date Time](https://docs.oracle.com/javase/tutorial/datetime/index.html)**.
Note: The java.util date-time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
If I got you right, this should solve your problem
public String nextMeet(int minutes, int seconds) {
LocalDateTime currentDate = LocalDateTime.now();
if ((currentDate.getMinute()*60) + currentDate.getSecond() > (minutes*60) + seconds) {
return (currentDate.getHour() + 1) + ":" + minutes + ":" + seconds;
} else {
return currentDate.getHour() + ":" + minutes + ":" + seconds;
}
}
I've found another solution myself. This library can parse a cron expression and return the next time when it will run, which solves most of my issues. (taken from this question)
Thanks to #OleV.V. for the idea.
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.
Is there an API to quickly manipulate (e.g. add, subtract) on time (hour, minute).
Pseudo code is listed below
Time t1 = "5 PM";
t1.add("5 minutes");
t1.subtract("90 minutes");
'course there is: http://download.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html#add%28int,%20int%29
You'll have to set the field parameter appropriately with one of the constants defined in the Field Summary section of the above page
java.time
The standard date-time library of Java SE 8 is rich with all such features.
Note: Quoted below is a notice at the Home Page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Given below is a demo of such features using java.time, the modern API:
import java.time.Duration;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalTime time = LocalTime.of(17, 30);
System.out.println(time);
time = time.plusMinutes(5);
System.out.println(time);
time = time.minusMinutes(90);
System.out.println(time);
// Parsing and formatting
DateTimeFormatter dtfInput = new DateTimeFormatterBuilder()
.appendPattern("h[:m[:s]] a") // Optional fields in square bracket
.parseCaseInsensitive() // Case-insensitive (AM/am/Am etc.)
.toFormatter(Locale.ENGLISH);
time = LocalTime.parse("5 PM", dtfInput);
System.out.println(time);
// Dealing with timezone?
ZonedDateTime zdt = ZonedDateTime.now().with(time);
System.out.println(zdt);
// Custom format
DateTimeFormatter timeAndZone12HourFormat = DateTimeFormatter.ofPattern("hh:mm:ss a'['VV']'");
DateTimeFormatter timeAndZone24HourFormat = DateTimeFormatter.ofPattern("HH:mm:ss'['VV']'");
System.out.println(zdt.format(timeAndZone12HourFormat));
System.out.println(zdt.format(timeAndZone24HourFormat));
// Adding/subtracting ISO 8601 Duration
Duration duration = Duration.parse("PT2H30M"); // 2 hours 30 minutes
zdt = zdt.plus(duration);
System.out.println(zdt.format(timeAndZone12HourFormat));
}
}
Output:
Learn more about java.time, the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.