How to add time period in Android program? - java

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 =)

Related

Get current time and check if time has passed a certain period

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

How to do time running using Java

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.

How to get month and day from given string? [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 8 years ago.
How can I get day and date from given Strings. For example:
String date="25-12-2014";
How to get date and day from given string?
Expected output is,
25
Thu
I got stuck when I tried this.
private static String getFormatedDate(String strDate) {
String result = "";
if(strDate != null) {
if (strDate.contains("-")) {
String[] dates = strDate.split("-");
for(int i=0;i<dates.length;i++) {
result = result + Utils.replaceDateFormat(dates[i].trim(),"MMM dd", "EE, M.dd") + ("-");
}
int lastIndex = result.lastIndexOf("-");
result = result.substring(0, lastIndex).trim();
}
else {
result = Utils.replaceDateFormat(strDate.trim(),"MMM dd", "EE, M.dd");
}
}
return result;
}
Utils:
public static String replaceDateFormat(String value, String actualFormat, String exceptedFormat) {
final int currentYear = Calendar.getInstance().get(Calendar.YEAR);
final SimpleDateFormat fromDate = new SimpleDateFormat(actualFormat);
final SimpleDateFormat toDate = new SimpleDateFormat(exceptedFormat);
Date convertedFromDate = null;
try {
convertedFromDate = fromDate.parse(value);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
final Calendar c1 = Calendar.getInstance();
c1.setTime(convertedFromDate);
c1.set(Calendar.YEAR, currentYear);
return toDate.format(c1.getTime());
}
Your methods are very convoluted for a relatively simple task. Why don't you use SimpleDateFormat? You can use the parse method. For example:
Date date = new SimpleDateFormat("dd-MM-yyyy").parse(string);
And then you can get the required fields from there.
EDIT
To get the day of the week, you were right with this code:
Date d = date.parse(result);
Calendar c = Calendar.getInstance();
c.setTime(d);
int day=c.get(Calendar.DAY_OF_WEEK);
And then if you want it in the format above, you could just make an array filled with the days of the week:
String[] daysOfWeek = new String[]{"Sun","Mon"... etc}
String day = daysOfWeek[day - 1];
You can use the method from Calendar:
String date = "25-12-2014";
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(format.parse(date));
int day = cal.get(Calendar.DAY_OF_MONTH);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
DateFormatSymbols symbols = new DateFormatSymbols(new Locale("en"));
String[] days = symbols.getShortWeekdays();
System.out.printf("%02d %3s\n", day, days[dayOfWeek]);
The symbols can be set to your Locale zone.
if you are allowed to use java 8 you can give LocalDate a chance:
String date = "25-12-2014";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate ld = LocalDate.parse(date, formatter);
System.out.println(ld.getDayOfMonth() + ", " + ld.getDayOfWeek());
Output is:
25, THURSDAY
EDIT:
System.out.println(ld.getDayOfMonth() + ", " + ld.getDayOfWeek().substring(0, 3));
#No aNoNym suggestion is right, with the following you get
25, THU

Summing time past 24 hours

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

convert a string of time to 24 hour format

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));
}
}

Categories