I have this Time object:
Time myTime = java.sql.Time.valueOf("15:33:00");
How can I add 30 minutes to myTime in Java? That means the new time will be 16:03:00
java.sql.Time myTime = java.sql.Time.valueOf("15:33:00");
LocalTime localtime = myTime.toLocalTime();
localtime = localtime.plusMinutes(30);
String output = localtime.toString();
you can get localTime straight away from the java.sql.time and you can use plusMinutes in LocalTime Api to add 30 minutes. this might help you check this
Here's an easy way to do it, using java.time.LocalDateTime:
package time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalField;
/**
* Created by Michael
* Creation date 4/24/2016.
* #link
*/
public class TimeDemo {
public static void main(String[] args) {
// Three three lines do the work
LocalDateTime localDateTime = LocalDateTime.of(2016, 4, 24, 9, 10);
LocalDateTime halfHourLater = localDateTime.plusMinutes(30); // Add 30 minutes
java.sql.Time sqlDateTime = new java.sql.Time(halfHourLater.toInstant(ZoneOffset.UTC).toEpochMilli()); //
// Printout just to check
System.out.println(DateTimeFormatter.ofPattern("yyyy-MMM-dd hh:mm:ss.SSS").format(halfHourLater));
System.out.println("java.time milliseconds: " + halfHourLater.toInstant(ZoneOffset.UTC).toEpochMilli());
System.out.println("System.currentMillis : " + System.currentTimeMillis());
}
}
Related
**I am trying to write the code for getting the date in required format , I have got the dates but how to add the required time with it ,
here I have
startDate - 1/08/2021 00:00:00 ,
EndDate - 20/08/2021 23:59:59 ,
increment days: 10
and the Expected output is :
05/08/2021 00:00:00 to 10/08/2021 23:59:59 , 11/08/2021 00:00:00 to 15/08/2021 23:59:59 ,
This is the Code which I was trying to write , any help is appreciated
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class DateTest {
public static List<LocalDate> getDaysBetweenDates(LocalDate startDate, LocalDate endDate, int interval) {
List<LocalDate> dates = new ArrayList<>();
while (endDate.isAfter(startDate)) {
dates.add(startDate);
startDate = startDate.plusDays(interval-1);
dates.add(startDate);
startDate = startDate.plusDays(1);
}
return dates;
}
public static void main(String[] args) {
int interval = 5;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss",Locale.US);
List<LocalDate> daysBetweenDates = getDaysBetweenDates(LocalDate.parse("01-08-2021 00:00:00", formatter),
LocalDate.parse("20-08-2021 23:59:59", formatter), interval);
System.out.println(daysBetweenDates);
}
}
Here's an alternative that uses LocalDates only (OK, and LocalDateTimes internally):
public static void printDaysInPeriod(LocalDate start, LocalDate end, int interval) {
// provide some data structure that
Map<LocalDate, LocalDate> intervals = new TreeMap<LocalDate, LocalDate>();
// loop through the dates in the defined period
while (start.isBefore(end)) {
// use the interval as step
LocalDate intervalEnd = start.plusDays(interval);
// store the sub-interval in the data structure
intervals.put(start, intervalEnd);
// and rearrange "start" to be the day after the last sub-interval
start = intervalEnd.plusDays(1);
}
// provide a formatter that produces the desired output per datetime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"dd/MM/uuuu HH:mm:ss"
);
// provide a data structure for the output parts (Strings here)
List<String> intervalOutput = new ArrayList<>();
// stream the sub-intervals
intervals.entrySet().forEach(e ->
// then produce the desired output per sub-interval and store it
intervalOutput.add(e.getKey().atStartOfDay()
.format(formatter)
+ " to "
+ e.getValue()
.atTime(LocalTime.MAX)
.format(formatter)));
// finally output the sub-interval Strings comma-separated
System.out.println(String.join(" , ", intervalOutput));
}
Using this method in a main, like this
public static void main(String[] args) {
// example dates defining an interval
String startInterval = "05/08/2021";
String endInterval = "15/08/2021";
// provide a parser that handles the format
DateTimeFormatter dateParser = DateTimeFormatter.ofPattern("dd/MM/uuuu");
// then parse the dates to LocalDates
LocalDate start = LocalDate.parse(startInterval, dateParser);
LocalDate end = LocalDate.parse(endInterval, dateParser);
// and use the method
printDaysInPeriod(start, end, 5);
}
produces the following output:
05/08/2021 00:00:00 to 10/08/2021 23:59:59 , 11/08/2021 00:00:00 to 16/08/2021 23:59:59
You changed your questions a few times and in the first reading, I thought that you have start and end Date-Times as String. Based on this understanding, I wrote this answer. However, the very next minute, deHaar posted this correct answer. I am leaving this answer here for someone who will be looking for a solution to this kind of requirement (i.e. with Date-Time as String).
You can do it in the following two simple steps:
Define separate DateTimeFormatter for the input and the output strings
Loop through the parse range of Date-Time.
Demo
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strStartDateTime = "1/08/2021 00:00:00";
String strEndDateTime = "20/08/2021 23:59:59";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("d/M/u H:m:s", Locale.ENGLISH);
LocalDateTime startDateTime = LocalDateTime.parse(strStartDateTime, dtfInput);
LocalDateTime endDateTime = LocalDateTime.parse(strEndDateTime, dtfInput);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
for (LocalDateTime ldt = startDateTime, nextDateTime = ldt.plusDays(10).minusSeconds(1); !ldt
.isAfter(endDateTime); ldt = ldt.plusDays(10), nextDateTime = ldt.plusDays(10).minusSeconds(1))
System.out.println(dtfOutput.format(ldt) + " - " + nextDateTime);
}
}
Output:
2021-08-01 00:00:00 - 2021-08-10T23:59:59
2021-08-11 00:00:00 - 2021-08-20T23:59:59
ONLINE DEMO
Learn more about 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.
Use the date-time API.
(The code should be self-explanatory.)
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class DateTest {
public static List<ZonedDateTime> getDaysBetweenDates(ZonedDateTime startDate, ZonedDateTime endDate, int interval) {
List<ZonedDateTime> dates = new ArrayList<>();
while (!startDate.isAfter(endDate)) {
dates.add(startDate);
if (Period.between(startDate.toLocalDate(), endDate.toLocalDate()).getDays() < interval) {
startDate = endDate;
}
else {
startDate = startDate.plusDays(interval);
}
dates.add(startDate);
startDate = startDate.plusDays(1);
}
return dates;
}
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss", Locale.ENGLISH);
List<ZonedDateTime> dates = getDaysBetweenDates(ZonedDateTime.of(LocalDateTime.parse("05/08/2021 00:00:00", formatter), ZoneId.systemDefault()),
ZonedDateTime.of(LocalDateTime.parse("15/08/2021 23:59:59", formatter), ZoneId.systemDefault()),
5);
for (int i = 0; i < dates.size(); i+=2) {
System.out.printf("%s to %s , ",
dates.get(i).format(formatter),
dates.get(i + 1).format(formatter));
}
}
}
Output when running above code as follows:
05/08/2021 00:00:00 to 10/08/2021 00:00:00 , 11/08/2021 00:00:00 to 15/08/2021 23:59:59 ,
I need to get the next datetime when it's say, 20.00 o'clock.
So for instance, if it's 13.00 hours, it'd give me the datetime corresponding to today at 20.00.
But if it's 21.00, it'd give me tomorrow at 20.00.
How can I achieve this? Is there some built in function that I just can't find the name of?
In a pinch I could also use Java Time instead of Joda Time.
Add one day to DateTime if the time is past 20:00.
Demo:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
public final class Main {
public static final void main(String[] args) {
// Test
System.out.println(getNextTime("13.00"));
System.out.println(getNextTime("21.00"));
}
static DateTime getNextTime(String strTime) {
LocalTime time = LocalTime.parse(strTime);
DateTime dt = DateTime.now(DateTimeZone.getDefault()).withTime(new LocalTime(20, 0));
if (time.isAfter(new LocalTime(20, 0))) {
dt = dt.plusDays(1);
}
return dt;
}
}
Output:
2021-03-29T20:00:00.000+01:00
2021-03-30T20:00:00.000+01:00
Note: Check the following notice at the Home Page of Joda-Time
Joda-Time is the de facto standard date and time library for Java
prior to Java SE 8. Users are now asked to migrate to java.time
(JSR-310).
Using the modern date-time API:
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public final class Main {
public static final void main(String[] args) {
// Test
System.out.println(getNextTime("13.00"));
System.out.println(getNextTime("21.00"));
}
static ZonedDateTime getNextTime(String strTime) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH.mm");
LocalTime time = LocalTime.parse(strTime, dtf);
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.systemDefault()).withHour(20);
if (time.isAfter(LocalTime.of(20, 0))) {
zdt = zdt.plusDays(1);
}
return zdt;
}
}
Output:
2021-03-29T20:00:18.325419+01:00[Europe/London]
2021-03-30T20:00:18.327587+01:00[Europe/London]
This question already has answers here:
Java Calendar adds a random number of milliseconds?
(4 answers)
Closed 2 years ago.
I am trying to format the date to ISO8601("yyyy-MM-dd'T'HH:mm:ss.SSSZ") using SimpleDateFormat, but formatted string seems to have random values at milliseconds place.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class DemoApplication {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
calendar.set(2020, 5 , 22, 17, 30, 00);
Date date = calendar.getTime();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String s = df.format(date);
System.out.println(s);
}
}
Output on multiple runs:
2020-06-22T17:30:00.886+0530
2020-06-22T17:30:00.049+0530
2020-06-22T17:30:00.799+0530
In the above output, everything is consistent except milliseconds after dot(.), Can someone explain this?
In the above output, everything is consistent except milliseconds
after dot(.), Can someone explain this?
The reason is that your format has milliseconds but you haven't set milliseconds in the Calendar instance; therefore, it gives you the milliseconds of the moment when you run your code.
You can verify the same using the following code:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
calendar.set(2020, 5, 22, 17, 30, 00);
Date date = calendar.getTime();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String s = df.format(date);
System.out.println(s);
System.out.println(date.toInstant().getNano()); // Added this line
}
}
Output:
2020-06-22T17:30:00.425+0100
425000000
On a side note, I recommend you stop using outdated date-time API and start using the modern date-time API.
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = LocalDateTime.of(2020, 5, 22, 17, 30, 00).atZone(ZoneId.systemDefault());
System.out.println(zdt);
}
}
Milliseconds aren't covered by
calendar.set(2020, 5 , 22, 17, 30, 00);
you can an extra Line to set them to 0:
calendar.set(Calendar.MILLISECOND, 0);
so that your program looks like this:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class DemoApplication {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
calendar.set(2020, 5 , 22, 17, 30, 00);
calendar.set(Calendar.MILLISECOND, 0);
Date date = calendar.getTime();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String s = df.format(date);
System.out.println(s);
}
}
The JavaDocs of java.util.Calendar state the following for the method getInstance():
Gets a calendar using the specified time zone and default locale. The Calendar returned is based on the current time in the given time zone with the default locale.
That means you are getting the actual moment and then by calendar.set(2020, 5 , 22, 17, 30, 00); you set year, month, day, hours, minutes and seconds but you are not changing the smaller units of time which will stay as they were when you called Calendar calendar = Calendar.getInstance(TimeZone.getDefault());. That's not random, it's the current millis at that very moment of calling getInstance().
For a possibility of setting the milliseconds of a Calendar to any specific value, have a look at the answer given by #Norwort.
I think you shouldn't be using the outdated datetime classes from java.util. Instead, use java.time, maybe like this:
public static void main(String[] args) throws ParseException {
ZonedDateTime zonedDateTime = ZonedDateTime.of(2020, 5, 22, 17, 30, 0, 0,
ZoneId.systemDefault());
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String s = zonedDateTime.format(dtf);
System.out.println(s);
}
Which prints
2020-05-22T17:30:00.000+0200
when executed on my system, which has an offset of +02:00 at the moment.
The output on your system might differ, but will have set milliseconds and smaller units of time to 0.
I have the following and I get the time back but I want to add hours to it. I'm not having luck. I have tried SimpleDateTime but cannot seem to get the syntax correct.
package com.sayitfast.service;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class TimeData {
private String time;
private Long milliseconds_since_epoch;
private String date;
#Override
public String toString() {
return "TimeData" + "time=" + time + ", milliseconds_since_epoch="
+ milliseconds_since_epoch + ", date=" + date;
}
public void TimeData() {
}
public void mytimdData() throws IOException {
String webPage = "http://time.jsontest.com";
InputStream is = nw URL(webPage).openStream();
final Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
Gson gson = new Gson();
TimeData td = gson.fromJson(reader, TimeData.class);
System.out.println(td.time);
}
}
You may need to add
String webPage = "http://time.jsontest.com";
InputStream is = new URL(webPage).openStream();
final Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
Gson gson = new Gson();
TimeData td = gson.fromJson(reader, TimeData.class);
System.out.println(td.toString());
System.out.println(td.getTime());
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = (Date)formatter.parse(td.getTime());
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 1);
Date dates = cal.getTime();
System.out.println(dates);
Here I have increased the time to 1hr. This is an example you can change as per your requirement
Also, you can use Date incrementedDate = DateUtils.addHour(date, 1); instead of Calender
I recommend you switch from the outdated and error-prone java.util date-time API to the rich set of modern date-time API and do it as follows (includes demo of some custom formats as well):
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(final String[] args) {
// Custom formats
DateTimeFormatter formatter24Hour = DateTimeFormatter.ofPattern("HH:mm:ss");
DateTimeFormatter formatter12Hour = DateTimeFormatter.ofPattern("hh:mm:ss a");
// Get the number of milliseconds from the epoch of 1970-01-01T00:00:00Z.
long epochMilli = Instant.now().toEpochMilli();
System.out.println("The number of milliseconds from the epoch is " + epochMilli);
System.out.println();
// Get Instant from the number of milliseconds from the epoch
Instant instant = Instant.ofEpochMilli(epochMilli);
// Get LocalDateTime from Instant
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());// Use the zone as per your requirement
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println("Date-time in your time-zone: " + ldt);
System.out.println("Time in your time-zone: " + ldt.format(DateTimeFormatter.ISO_LOCAL_TIME));
System.out.println("Time in your time-zone: " + ldt.format(formatter24Hour));
System.out.println("Time in your time-zone: " + ldt.format(formatter12Hour));
System.out.println();
// Add some hours e.g. 2 hours to LocalDateTime
LocalDateTime newDateTime = ldt.plus(2, ChronoUnit.HOURS);
System.out.println("Date-time in your time-zone after 2 hours: " + newDateTime);
}
}
Output:
The number of milliseconds from the epoch is 1593532251048
Date-time in your time-zone: 2020-06-30T16:50:51.048
Time in your time-zone: 16:50:51.048
Time in your time-zone: 16:50:51
Time in your time-zone: 04:50:51 pm
Date-time in your time-zone after 2 hours: 2020-06-30T18:50:51.048
The code below seems to convert to BST instead. Am I doing something silly?
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
public class Test {
#Test
public void testTimeInterval(){
String DAY_SHIFT="08:00-17:15";
System.out.println(toInterval(DAY_SHIFT, "America/New_York", "UTC"));
}
public static final String TIME_FORMAT = "HH:mm";
public static List<LocalTime> toInterval(String str, String sourceTZ, String destTZ) {
if (!StringUtils.isBlank(str)){
final DateTimeFormatter timeFormat = DateTimeFormat.forPattern(TIME_FORMAT).withZone(DateTimeZone.forID(sourceTZ));
String[] tokens = str.split("-");
if (tokens!=null && tokens.length==2){
try{
long start = timeFormat.parseMillis(tokens[0]);
long end = timeFormat.parseMillis(tokens[1]);
DateTime startTime = new DateTime(start, DateTimeZone.forID(sourceTZ)).toDateTime(DateTimeZone.forID(destTZ));
DateTime endTime = new DateTime(end, DateTimeZone.forID(sourceTZ)).toDateTime(DateTimeZone.forID(destTZ));
return Arrays.asList(new LocalTime(startTime, DateTimeZone.forID(destTZ)),
new LocalTime(endTime, DateTimeZone.forID(destTZ)));
}
catch (IllegalArgumentException e){
e.printStackTrace();
}
}
};
return null;
}
}
The above code prints [13:00:00.000, 22:15:00.000]. According to this link, it's an hour off should be [12:00:00.000, 21:15:00.000]
You've only provided a time of day. What day are you interested in? That will affect the mapping to UTC. If you mean today, you should specify that explicitly. It looks like you really want to parse to a LocalTime, then construct an appropriate LocalDateTime by joining that with some appropriate LocalDate (which will depend on what you're trying to achieve).
My guess is that it's actually doing it for January 1st 1970 - at which point the UTC offset of New York was -5, not -4. You can verify that by logging startTime and endTime in full.
Also for simplicity, I'd strongly recommend calling DateTimeZone.forId just twice, at the start of the method instead of every time you need a zone.
You should also consider what you want to happen if the local date/time is ambiguous, or potentially skipped due to DST transitions. If you pick a date which doesn't include any transitions, this will never happen of course.