I have start_time and end_Time, so I tried to print those interval_times (time format 24).
How do I do it?
int start = Integer.parseInt("10:24:49");
int end = Integer.parseInt("11:24:49");
for (int i = start; i < end; i++)
{
System.out.println("result i ="+ i);
}
Since Java 8, the java.time package has been the optimal way to do all date/time related things.
It takes some getting used to, e.g. when it comes to timezones, but it's absolutely worth the effort!
Here's the code for your seconds printer:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public static void main(final String[] args) {
// Just so you know it in the future. Not needed in this example.
final DateTimeFormatter dtfDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.US);
final DateTimeFormatter dtfTime = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.US);
final LocalTime ltStart = LocalTime.of(10, 24, 49);
final LocalTime ltEnd = ltStart.plusHours(1);
// If you want to use String parsing to get your instance:
final LocalTime ltStartViaParsing = LocalTime.from(dtfTime.parse("10:24:49"));
LocalTime i = ltStart;
while (i.isBefore(ltEnd)) {
System.out.println("result i = " + dtfTime.format(i));
i = i.plusSeconds(1);
}
}
Output:
result i = 10:24:49
result i = 10:24:50
result i = 10:24:51
...
result i = 11:24:46
result i = 11:24:47
result i = 11:24:48
It looks like you want to run the loop for particular duration of time.
In case you want to run the loop for fixed duration like for 5 minutes, with a 5 second interval, you can do it like this:
try {
// This loop will run for 5 minutes for every 5 second delay
for(int i=0;i<60;i++) {
System.out.println(new Date());
Thread.sleep(5 * 1000);
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
Before using, see comments below.
If you are intending to print every hour between two given times, then you are totally on the wrong path.
Integer.parseInt
It is intended to get a String number and converts it to Java Integer.
Try to use SimpleDateFormat and Date and Calendar
String startTime = "10:24:49";
String endTime = "11:24:49";
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(startTime));
int start = calendar.get(Calendar.HOUR_OF_DAY);
calendar.setTime(sdf.parse(endTime));
int end = calendar.get(Calendar.HOUR_OF_DAY);
This may help:
DateTime startTime, endTime;
Period p = new Period(startTime, endTime);
int hours = p.getHours();
int minutes = p.getMinutes();
And also you can use Java.util.Timer to schedule a thread to be executed at a certain time in the future.
Related
this code below gets the current time and timezone of the area
Date date = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(TimeZone.getDefault());
System.out.println("Time: " + df.format(date));
right now its 1:01 pm (at the time of typing)
what i need help doing is implementing a feature in the code that checks if the current time has passed, for example 1:00PM
but I have no idea where to even start, can you help me out?
Use the Java 8+ Time API class LocalTime:
LocalTime refTime = LocalTime.of(13, 0); // 1:00 PM
// Check if now > refTime, in default time zone
LocalTime now = LocalTime.now();
if (now.isAfter(refTime)) {
// passed
}
// Check if now >= refTime, in pacific time zone
LocalTime now = LocalTime.now(ZoneId.of("America/Los_Angeles"))
if (now.compareTo(refTime) >= 0) {
// passed
}
I see it has already answered with Time, but as a teaching point, if you really wanted to use Date, you could have done something like this:
public static void main(String[] args) {
Date date = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(TimeZone.getDefault());
System.out.println("Time: " + df.format(date));
//If you print the date you'll see how it is formatted
//System.out.println(date.toString());
//So you can just split the string and use the segment you want
String[] fullDate = date.toString().split(" ");
String compareAgainstTime = "01:00PM";
System.out.println(isPastTime(fullDate[3],compareAgainstTime));
}
public static boolean isPastTime(String currentTime, String comparedTime) {
//We need to make the comparison time into the same format as the current time: 24H instead of 12H:
//then we'll just convert the time into only minutes to that we can more easily compare;
int comparedHour = comparedTime[-2].equals("AM") ? String.valueOf(comparedTime[0:2]) : String.valueOf(comparedTime[0:2] + 12 );
int comparedMin = String.valueOf(comparedTime[3:5]);
int comparedT = comparedHour*60 + comparedMin;
//obviously currentTime is alredy the correct format; just need to convert to minutes
int currentHour = String.valueOf(currentTime[0:2]);
int currentMin = String.valueOf(currentTime[3:5]);
int currentT = currentHour*60 + currentMin;
return (currentT > comparedT);
}
It's a bit messier, having to muddy into the Strings and whatnot, but it is possible. You would also have to be careful the zero-pad the comparedTime or just check for that in the function
I'm writing an aplication for Android and I need to add "sleep time" period in my program. I don't know how to implement this. I have a sevice in my program and service must be switched off during certain periods of time (eg 22:00 - 7:00). Advise whether there is any ready solution for this kind of problem? I'm interested in is how to set this time period, thank you. Sorry for my English.
You may try to add this to get the current date and time:
String str = DateFormat.getDateTimeInstance().format(new Date());
After that you can check that the time is within the range you want.
public static final String myformat = "HH:mm";
private Date date;
private Date time1;
private Date time2;
private String range1 = "10:00";
private String range2 = "07:00";
SimpleDateFormat str = new SimpleDateFormat(myformat, Locale.US);
private void checkRange(){
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
date = parseDate(hour + ":" + minute);
time1= parseDate(range1);
tim2= parseDate(range2);
if ( time1.before( date ) && time2.after(date)) {
//code
}
}
Eventually written following function using JodaTime:
SharedPreferences sp = context.getSharedPreferences(Constants.SP_SETTINGS,Context.MODE_PRIVATE);
String start = sp.getString(Constants.PARAM_SLEEP_MODE_START,null);
String end = sp.getString(Constants.PARAM_SLEEP_MODE_END,null);
if (start==null || end ==null) return null;
DateTime now = new DateTime(new Date());
Days days = Days.daysBetween(new DateTime(new Date(0)).toLocalDate(),now.toLocalDate());
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
DateTime begin = formatter.parseDateTime(start).plusDays(days.getDays());
DateTime finish = formatter.parseDateTime(end).plusDays(days.getDays());
if (begin.isAfter(finish)) {
if (now.isBefore(finish)) begin = begin.minusDays(1);
else finish = finish.plusDays(1);
} else {
if (now.isAfter(finish)) {
begin = begin.plusDays(1);
finish = finish.plusDays(1);
}
}
Interval interval = new Interval(begin,finish);
return interval.contains(now);
It is very well defines what I want. Thank you all =)
I have the following method to sum time:
public static String sumTime(String date1, String date2) throws ParseException {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
Date d1 = formatter.parse(date1);
Date d2 = formatter.parse(date2);
calendar.setTime(d2);
d1 = DateUtils.addHours(d1, calendar.get(Calendar.HOUR_OF_DAY));
d1 = DateUtils.addMinutes(d1, calendar.get(Calendar.MINUTE));
d1 = DateUtils.addSeconds(d1, calendar.get(Calendar.SECOND));
d1 = DateUtils.addMilliseconds(d1, calendar.get(Calendar.MILLISECOND));
return formatter.format(d1);
}
DateUtils is from Apache Commons Lang 3
It works quite well for what I want, unless the sum is bigger than 24 hours.
For example:
String time = "00:00:00.000";
try {
for (int i = 0; i < 24; i++) {
time = sumTime(time, "01:00:00.123");
}
System.out.println(time);
} catch (ParseException e) {
e.printStackTrace();
}
The result is:
00:00:02.952
But this is what I'd like it to be:
24:00:02.952
Is there any (easy) way to accomplish that?
I don't mind using different libraries/methods, as long as I get the correct result.
Keep in mind that time will always start in 00:00:00.000;
Have you thought about using days to represent each set of 24 hours? You could add something in your sumTime method, and have it add days. SimpleDateFormater can use days, maybe this will help:
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
java.util.Date is not so strong in this area. See the Joda Time for a library that handles this properly.
I don't have access to an installation just now. The code will be close to this:
DateTimeFormatter dtf = DateTimeFormat.forPattern("HH:mm:ss.SSS");
DateTime start = dtf.parseDateTime(date1);
DateTime end = dtf.parseDateTime(date2);
PeriodFormatter pf = new PeriodFormatterBuilder()
.printZeroAlways().appendHours().appendSeparator(":")
.appendMinutes().appendSeparator(":")
.appendSeconds().appendSeparator(":")
.appendMillis3Digit().toFormatter();
return pf.print(new Period(start, end, PeriodType.time()));
Date is not the right thing class to use. Date is a instant of time, not a "Date Difference".
The right thing to do will be to use a library like Joda Time as someone has already suggested. If you don't want to do so - here's a possible alternative:
Parse the string into hours, minutes and seconds yourself, and then add it yourself.
I would encourage you to look into a "well accepted" library though. There may be things I'm not thinking of in my solution. Also, you have add all the error checking.
Here's the starter code:
public class TimeInterval {
short milliSeconds;
short seconds;
short minutes;
int hours;
public TimeInterval (String dateString) {
// HHHHHH:MI:SS.SSS
Pattern pattern = Pattern.compile("(\\d+):(\\d\\d):(\\d\\d)\\.(\\d\\d\\d)");
Matcher matcher = pattern.matcher(dateString);
if ( matcher.find() ) {
hours = Integer.parseInt(dateString.substring(matcher.start(1), matcher.end(1)));
minutes = Short.parseShort(dateString.substring(matcher.start(2), matcher.end(2)));
seconds = Short.parseShort(dateString.substring(matcher.start(3), matcher.end(3)));
milliSeconds = Short.parseShort(dateString.substring(matcher.start(4), matcher.end(4)));
}
}
private TimeInterval() {
}
public TimeInterval add(TimeInterval interval) {
TimeInterval ret = new TimeInterval();
ret.milliSeconds = (short) ((interval.milliSeconds + milliSeconds)%1000);
int carry = (interval.milliSeconds + milliSeconds)/1000;
ret.seconds = (short) ((interval.seconds + seconds)%60 + carry );
carry =(interval.seconds + seconds)/60;
ret.minutes = (short) ((interval.minutes + minutes)%60 + carry);
carry = (interval.minutes + minutes)/60;
ret.hours = (interval.hours + hours + carry);
return ret;
}
#Override
public String toString() {
return String.format("%d:%02d:%02d.%03d", hours, minutes, seconds, milliSeconds);
}
}
Using this class your program will be like :
TimeInterval time = new TimeInterval("00:00:00.000");
try {
for (int i = 0; i < 24; i++) {
time = time.add(new TimeInterval("01:00:00.123"));
}
System.out.println(time.toString());
} catch (ParseException e) {
e.printStackTrace();
}
Have you tried Joda-Time which actually has direct support for this sort of thing?
PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
builder.printZeroAlways()
.minimumPrintedDigits(2)
.appendHours()
.appendSeparator(":").appendMinutes()
.appendSeparator(":").appendSeconds()
.appendSeparator(".").appendMillis3Digit();
PeriodFormatter formatter = builder.toFormatter();
PeriodParser parser = builder.toParser();
String s1 = "11:00:00.111";
String s2 = "23:00:00.111";
MutablePeriod p1 = new MutablePeriod();
MutablePeriod p2 = new MutablePeriod();
parser.parseInto(p1, s1, 0, Locale.getDefault());
parser.parseInto(p2, s2, 0, Locale.getDefault());
p1.add(p2);
System.out.println(formatter.print(p1));
Prints
34:00:00.222
I have a string holding a start time and an end time in this format 8:30AM - 9:30PM I want to be able to strip out the AM - and the PM and convert all the times to 24 hour format so 9:30PM would really be 21:30 and also have both the times stored in 2 different variables, I know how to strip the string into substrings but Im not sure about the conversion, this is what I have so far. the time variable starts out holding 8:30AM - 9:30PM.
String time = strLine.substring(85, 110).trim();
//time is "8:30AM - 9:30PM"
String startTime;
startTime = time.substring(0, 7).trim();
//startTime is "8:30AM"
String endTime;
endTime = time.substring(9).trim();
//endTime "9:30AM"
Working code (considering that you managed to split the Strings):
public class App {
public static void main(String[] args) {
try {
System.out.println(convertTo24HoursFormat("12:00AM")); // 00:00
System.out.println(convertTo24HoursFormat("12:00PM")); // 12:00
System.out.println(convertTo24HoursFormat("11:59PM")); // 23:59
System.out.println(convertTo24HoursFormat("9:30PM")); // 21:30
} catch (ParseException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Replace with KK:mma if you want 0-11 interval
private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mma");
// Replace with kk:mm if you want 1-24 interval
private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm");
public static String convertTo24HoursFormat(String twelveHourTime)
throws ParseException {
return TWENTY_FOUR_TF.format(
TWELVE_TF.parse(twelveHourTime));
}
}
Now that I think about it, SimpleDateFormat, H h K k can be confusing.
Cheers.
You need to use: SimpleDateFormat
And can refer this tutorial: Formatting hour using SimpleDateFormat
Example:
//create Date object
Date date = new Date();
//formatting hour in h (1-12 in AM/PM) format like 1, 2..12.
String strDateFormat = "h";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
System.out.println("hour in h format : " + sdf.format(date));
I wouldn't reinvent the wheel (unless you are doing this as a school project or some such).
Just get a date object out of your time stamp and then you can generate whatever format you want with this: SimpleDateFormat
[edited to address your specific request]
if you absolutely need to work from your own unique strings, then you'll do something like this (I don't know exactly what your strings look like... you're using offsets like 85, which means nothing out of context).
I didn't check this for bugs, but this is approximately what you want...
myStr = timestampString.toLowerCase(); //something like 8:30am
boolean add12 = (myStr.indexOf("pm") != -1)?true:false;
//convert hour to int
int hour = Integer.parseInt(myStr.split(":")[0]);
int minutes = Integer.parseInt( myStr.split(":")[1].replaceAll("\\D+","").replaceAll("^0+","") ); //get the letters out of the minute part and get a number out of that, also, strip out leading zeros
int militaryTime = hour + (add12)? 12:0;
if(!add12 && militaryTime == 12)
militaryTime = 0; //account for 12am
//dont' forget to add the leading zeros back in as you assemble your string
With Joda Time, the code looks like:
DateTimeFormatter formatter12 = DateTimeFormat.forPattern("K:mma");
DateTime begin = formatter12.parseDateTime(beginTime);
DateTime end = formatter12.parseDateTime(endTime);
DateTimeFormatter formatter24 = DateTimeFormat.forPattern("k:mma");
String begin24 = formatter24.print(begin);
String end24 = formatter24.print(end);
I should like to contribute the modern answer
DateTimeFormatter twelveHourFormatter = DateTimeFormatter.ofPattern("h:mma", Locale.ENGLISH);
String time = "8:30AM - 9:30PM";
String[] times = time.split(" - ");
LocalTime start = LocalTime.parse(times[0], twelveHourFormatter);
System.out.println(start.toString());
LocalTime end = LocalTime.parse(times[1], twelveHourFormatter);
System.out.println(end.toString());
This prints:
08:30
21:30
I am using java.time, the modern Java date and time API. The SimpleDateFormat class used in many of the other answers is long outdated and was always troublesome. java.time is so much nicer to work with than the date-time classes from the 1990’s. A LocalTime is a time of day without a date (and without time zone), so suits your need much better than an old-fashioned Date.
Link: Oracle tutorial: Date Time explaining how to use java.time.
24 hour time adds 12 to any time greater than 12pm so that 1pm is 13 and so on until 24 or 12am. Here is the sudo code:
if(hour <= 12)
{
hour = hour + 12;
}
All the below lines will works when
String str="07:05:45PM";
and when you call timeConversion(str) and want to convert to 24 hours format..
public class TimeConversion {
private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mm:ssa");
private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm:ss");
static String timeConversion(String s) {
String str = null;
try {
str= TWENTY_FOUR_TF.format(
TWELVE_TF.parse(s));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public static void main(String[] args) throws ParseException {
String str="07:05:45PM";
System.out.println(timeConversion(str));
}
}
I know how to convert local time to UTC time and vice versa.
But I am very much confused about daylight savings time(DST) handling while doing this.
So can anyone answer the below questions:
1. Does java internally handle DST when converting between timezones?
2. What things I need to do while converting between timezones?
3. Any good article which explains about this more clearly?
Thanks in advance.
Are you sure you know how to convert dates to UTC and back? Correctly?
I am afraid, I doubt that.
Yes.
You don't need to convert, you just need to assign correct TimeZone.
What you need an article for? OK, I am working on this, but for now let me put an answer here.
The first thing first. Your program should store Date (or Calendar) in UTC TimeZone internally. Well, in fact in GMT, because there are no leap seconds in Java, but that is another story.
The only place when you should be in need of "converting", is when you are going to display the time to user. That regards to sending email messages as well. In both cases you need to format date to get its textual representation. To that you would use DateFormat and assign correct TimeZone:
// that's for desktop application
// for web application one needs to detect Locale
Locale locale = Locale.getDefault();
// again, this one works for desktop application
// for web application it is more complicated
TimeZone currentTimeZone = TimeZone.getDefault();
// in fact I could skip this line and get just DateTime instance,
// but I wanted to show how to do that correctly for
// any time zone and locale
DateFormat formatter = DateFormat.getDateTimeInstance(
DateFormat.DEFAULT,
DateFormat.DEFAULT,
locale);
formatter.setTimeZone(currentTimeZone);
// Dates "conversion"
Date currentDate = new Date();
long sixMonths = 180L * 24 * 3600 * 1000;
Date inSixMonths = new Date(currentDate.getTime() + sixMonths);
System.out.println(formatter.format(currentDate));
System.out.println(formatter.format(inSixMonths));
// for me it prints
// 2011-05-14 16:11:29
// 2011-11-10 15:11:29
// now for "UTC"
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(formatter.format(currentDate));
System.out.println(formatter.format(inSixMonths));
// 2011-05-14 14:13:50
// 2011-11-10 14:13:50
As you can see, Java cares about handling DST. You can of course handle it manually, just read the TimeZone related JavaDoc.
Here is the best solution that I've found. I'm copying it here, but the solution came from http://biese.wordpress.com/2014/02/28/the-easy-way-to-convert-local-time-to-utc-time/.
package com.test.timezone;
import java.util.TimeZone;
public final class Utility {
public static final TimeZone utcTZ = TimeZone.getTimeZone("UTC");
public static long toLocalTime(long time, TimeZone to) {
return convertTime(time, utcTZ, to);
}
public static long toUTC(long time, TimeZone from) {
return convertTime(time, from, utcTZ);
}
public static long convertTime(long time, TimeZone from, TimeZone to) {
return time + getTimeZoneOffset(time, from, to);
}
private static long getTimeZoneOffset(long time, TimeZone from, TimeZone to) {
int fromOffset = from.getOffset(time);
int toOffset = to.getOffset(time);
int diff = 0;
if (fromOffset >= 0){
if (toOffset > 0){
toOffset = -1*toOffset;
} else {
toOffset = Math.abs(toOffset);
}
diff = (fromOffset+toOffset)*-1;
} else {
if (toOffset <= 0){
toOffset = -1*Math.abs(toOffset);
}
diff = (Math.abs(fromOffset)+toOffset);
}
return diff;
}
}
package com.test.timezone;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class TestTimezone {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss zzzz");
Calendar date1 = new GregorianCalendar(2014,0,15,10,0,0);
System.out.println(sdf.format(date1.getTime())+"\n");
long utcTimeStamp = Utility.toUTC(date1.getTimeInMillis(), date1.getTimeZone());
Calendar utcCal = Calendar.getInstance();
utcCal.setTimeInMillis(utcTimeStamp);
System.out.println("toUTC: "+sdf.format(utcCal.getTime())+"\n");
System.out.println("---------------------------------------");
Calendar date2 = new GregorianCalendar(2014,2,15,10,0,0);
System.out.println(sdf.format(date2.getTime())+"\n");
utcTimeStamp = Utility.toUTC(date2.getTimeInMillis(), date2.getTimeZone());
utcCal.setTimeInMillis(utcTimeStamp);
System.out.println("toUTC: "+sdf.format(utcCal.getTime())+"\n");
System.out.println("---------------------------------------");
Calendar date3 = new GregorianCalendar(2014,11,25,9,0,0);
System.out.println(sdf.format(date3.getTime())+"\n");
long uTime = Utility.toUTC(date3.getTimeInMillis(), date3.getTimeZone());
System.out.println("utcTimeStamp: "+uTime+"\n");
long lTime = Utility.toLocalTime(uTime, TimeZone.getTimeZone("EST"));
Calendar locCal = Calendar.getInstance();
locCal.setTimeInMillis(lTime);
System.out.println("toLocal: "+sdf.format(locCal.getTime())+"\n");
System.out.println("---------------------------------------");
Calendar date4 = new GregorianCalendar(2014,6,4,9,0,0);
System.out.println(sdf.format(date4.getTime())+"\n");
uTime = Utility.toUTC(date4.getTimeInMillis(), date4.getTimeZone());
System.out.println("utcTimeStamp: "+uTime+"\n");
lTime = Utility.toLocalTime(uTime, TimeZone.getTimeZone("EST"));
locCal = Calendar.getInstance();
locCal.setTimeInMillis(lTime);
System.out.println("toLocal: "+sdf.format(locCal.getTime())+"\n");
}
}
The code in TALE's answer can be simplified:
public final class Utility {
public static long toLocalTime(long time, TimeZone to) {
return time + to.getOffset(time);
}
public static long toUTC(long time, TimeZone from) {
return time - from.getOffset(time);
}
}