I have this time:
String myTime = "14:10";
Now I want to add 10 minutes to this time, so that it would be 14:20
How can I achieve this?
Something like this
String myTime = "14:10";
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Date d = df.parse(myTime);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.MINUTE, 10);
String newTime = df.format(cal.getTime());
As a fair warning there might be some problems if daylight savings time is involved in this 10 minute period.
I would use Joda Time, parse the time as a LocalTime, and then use
time = time.plusMinutes(10);
Short but complete program to demonstrate this:
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
LocalTime time = formatter.parseLocalTime("14:10");
time = time.plusMinutes(10);
System.out.println(formatter.print(time));
}
}
Note that I would definitely use Joda Time instead of java.util.Date/Calendar if you possibly can - it's a much nicer API.
Use Calendar.add(int field,int amount) method.
Java 7 Time API
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
LocalTime lt = LocalTime.parse("14:10");
System.out.println(df.format(lt.plusMinutes(10)));
You need to have it converted to a Date, where you can then add a number of seconds, and convert it back to a string.
I used the code below to add a certain time interval to the current time.
int interval = 30;
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Calendar time = Calendar.getInstance();
Log.i("Time ", String.valueOf(df.format(time.getTime())));
time.add(Calendar.MINUTE, interval);
Log.i("New Time ", String.valueOf(df.format(time.getTime())));
You have a plenty of easy approaches within above answers.
This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.
String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
Output :
14:10
14:20
I would recommend storing the time as integers and regulate it through the division and modulo operators, once that is done convert the integers into the string format you require.
Related
I have two strings which can be seen as time stamps:
String min="2017-04-15 13:27:31";
String max="2017-04-15 13:40:01";
Assume we want to find out the time passed from first time stamp to the second one. If there was only the time and no date included, I could get it using my following code:
String[] partsMin=min.split(":");
String[] partMax=max.split(":");
int diffZero=Integer.parseInt(partMax[0])-Integer.parseInt(partsMin[0]);
int diffOne=Integer.parseInt(partMax[1])-Integer.parseInt(partsMin[1]);
int diffOTwo=Integer.parseInt(partMax[2])-Integer.parseInt(partsMin[2]);
diffInSec=diffZero*3600+diffOne*60+diffOTwo;
So here is the question. How to get the job done while there is a date within the time stamp?
I would construct LocalDateTime instances from it.
Then i would get the milliseconds from it and substract startTime from EndTime.
What is remaining are the milliseconds passed between the two. A DateTimeFormatter is helpful as well for this purpose.
String strMin = "2017-04-15 13:27:31";
DateTimeFormatter formatterTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTimeMin = LocalDateTime.parse(strMin, formatter);
String strMax = "2017-04-15 13:40:01";
LocalDateTime dateTimeMax = LocalDateTime.parse(strMax, formatter);
long minutes = ChronoUnit.MINUTES.between(dateMin, dateMaxto);
long hours = ChronoUnit.HOURS.between(dateMin, dateMax);
If you want to get the milliseconds:
long millisPassed = dateMax.toEpochMilli() - dateMax.toEpochMilli();
Use the java date time libraries (even the old Date class would be fine for this) to parse the string into a proper object.
Depending on the date time library you chose you can then look at the difference between them. The simplest would be something like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date1 = sdf.parse(str1);
Date date2 = sdf.parse(str2);
long differenceInSeconds = (date2.getTime()-date1.getTime())/1000;
The new Java 8 time classes would also allow you to do this and would be better to learn going forwards. I can't remember the syntax for that off the top of my head though.
Did you try with replace all the other part of your String like this :
String[] partsMin = min.replaceAll("\\d+-\\d+-\\d+", "").trim().split(":");
String[] partMax = max.replaceAll("\\d+-\\d+-\\d+", "").trim().split(":");
Doing this in your code:
int diffZero=Integer.parseInt(partMax[0])
is the same as doing:
int diffZero=Integer.parseInt("2017-04-15")
that is generating an Exception(NumberFormatException)
you should better try to PARSE those strings min and max into a date
Edit:
you can inspect your code/ variables: and see that splitting to ":" is not giving you back the correct array since the element at index 0 is holding more information than you need...
but as I said before, you are going on the wrong path, dont re invent the wheel and look how practical will get using the APIs that java has for us:
String min = "2017-04-15 13:27:31";
String max = "2017-04-15 13:40:01";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTimeMin = LocalDateTime.parse(min, formatter);
LocalDateTime dateTimeMax = LocalDateTime.parse(max, formatter);
long days = ChronoUnit.DAYS.between(dateTimeMin, dateTimeMax);
long minutes = ChronoUnit.MINUTES.between(dateTimeMin, dateTimeMax);
System.out.println(days);
System.out.println(minutes);
use SimpleDateFormat to parse the date string, and do operation on Date result, you will get right value. This works well for date between '2017-02-28 23:59:59' and '2017-03-01 00:00:01'
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = format.parse("2017-02-28 23:59:59");
Date date2 = format.parse("2017-03-01 00:00:01");
long time1 = date1.getTime();
long time2 = date2.getTime();
long diff = time2 - time2; // should be 2000
I just want to subtract 1 hour from a DateTime I tried looking it up on Google and I found that there is a method called minus that takes a copy of the date and take a specific duration right here: http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#minus(long)
But I don't know how to use it and I can't an find a example on the internet.
Here's my code:
String string1 = (String) table_4.getValueAt(0, 1);
String string2= (String) table_4.getValueAt(0, 2);
DateTimeFormatter dtf = DateTimeFormat.forPattern("hh:mm a").withLocale(Locale.ENGLISH);
DateTime dateTime1 = dtf.parseDateTime(string1.toString());
DateTime dateTime2 = dtf.parseDateTime(string2.toString());
final String oldf = ("hh:mm a");
final String newf= ("hh.mm 0");
final String newf2= ("hh.mm a");
final String elapsedformat = ("hh.mm");
SimpleDateFormat format2 = new SimpleDateFormat(oldf);
SimpleDateFormat format2E = new SimpleDateFormat(newf);
Period timePeriod = new Period(dateTime1, dateTime2);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendHours().appendSuffix(".")
.appendMinutes().appendSuffix("")
.toFormatter();
String elapsed = formatter.print(timePeriod);
table_4.setValueAt(elapsed,0,3);
DecimalFormat df = new DecimalFormat("00.00");
System.out.println(dateTime1);
table_4.setValueAt("", 0, 4);
table_4.setValueAt("", 0, 5);
Sample Data:
dateTime1: 08:00 AM
dateTime2: 05:00 PM
the period will be 9 hours. but i want it to be 8 hrs only because i want to subtract the lunch break in my program.
i tried it with this stupid code:
dateTime1.minus(-1)
I also tried parsing string1 to double so I can subtract it by one.
double strindtoD = Integer.parseInt(string1);
I also tried making another DateTime and use period to get the difference of the two time
String stringOneHour = ("01:00 AM");
DateTime dateTime3 = dtf.parseDateTime(stringOneHour.toString());
Period timePeriod = new Period(dateTime3, dateTime1);
Just use:
dateTime.minusHours(1)
This is documented in the API.
Note that DateTime objects are immutable, so the operation alone has no effect. You need to assign the result of this method to a new object (or replace itself):
dateTime = dateTime.minusHours(1);
As to how to obtain a Period out of the difference between two DateTimes, you must first go through an Interval:
Period period = new Interval(begin, end).toPeriod();
Link to a SO post explaining why there is both Period and Interval.
Side note: Joda Time uses a LOT of indirections in its API; as such reading the Javadoc not only requires one to read the methods for one class, but also look at the list of inherited methods from all the inherited abstract classes/interfaces; for instance, a DateTime is also a ReadableInstant. One you get used to it, though, it's a breeze.
If you are using an older version of org.joda.time.DateTime then you can use minus(ReadablePeriod period) method like this
Date date = LocalDate.now().minus(new Period(1, 0, 0, 0)).toDate();
where Period accepts int hours, int minutes, int seconds, int millis parameters
By using Calender class object you can use this method to subtract hours.
cal.add(Calendar.HOUR_OF_DAY, -numberOfHours);
and also here is complete example link
I'm trying to get a time string in the format of YYYYMMDD-HHMMSSMilliseconds in Android
Ex: 20130312-1723437520 (2013 March 12th, 17 Hour 23 Minutes 43 Seconds 7520 Milliseconds)
Time now = new Time();
now.setToNow();
String snapshotTime = now.format("yyyyMMdd-HHmmss");
First of all, above code doesn't even work properly. snapshotTime is always set to the format string itself.
Second of all, according to the Android documentation, there's no way to record milliseconds.
How can I accomplish this?
See the SimpleDateFormat class, you can format a Date object into the required format (upper-case S will give millis)
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String str = fmt.format(now);
That said, using Joda Time is usually a good idea (Proguard will strip code you don't use).
You'll have to use the strftime formatting, as noted in the Android docs.
Time now = new Time();
now.setToNow();
String snapshotTime = now.format("%Y%m%d-%H%M%S");
If you really want to use milliseconds than I would recommend SimpleDateFormat.
Try getting the time as unix timestamp with milliseconds from
long currentTime = System.currentTimeMillis();
or convert your time to milliseconds:
long currentTime = now.toMillis(true);
Then you can convert this to your desired date:
Time now = new Time();
now.set(currentTime);
String snapshotTime = now.format("%Y%m%d-%H%M%S")+""+(currentTime%1000);
Didn't test it but hope it works :)
I would recommend to use this little library, it's very helpful when working with dates. Have a look at the DateTimeFormatter class.
As an alternative use Calendar and SimpleDateFormater (you'll have to adjust the format string of course, see this for explanation of the symbols)
Calendar c = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-SSSS");
String date = sdf.format(c.getTime());
You can try this:
public static String format() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmssSSS");
Date now = new Date();
return simpleDateFormat.format(now);
}
First of all forgive my English :-(
I have a problem with hours on java. Let's see it by an example:
DateFormat datos = new SimpleDateFormat ("hh:mm:ss");
Date ac, lim;
String actual,limit;
actual="18:01:23";
limit="00:16:23";
ac=datos.parse(actual);
lim=datos.parse(limit);
if(ac.compareTo(lim)==-1){.......
I need to solve this case in which limit is past midnight and actual hour is before midnight. My program says that actual has reached limit and it isn't correct because at the example, it has still 6 hours to finish.
I tried to solve it with DateFormat class but it doesnt see this case. I tried it with Time class too but its methods are deprecated.
How can I solve this?
Use HH instead of hh in your SimpleDateFormat:
DateFormat datos = new SimpleDateFormat("HH:mm:ss");
hh is the 12-hour clock (hours go from 1 to 12).
HH is the 24-hour clock (hours go from 0 to 23).
But besides that, there are other things wrong with this. Class Date is not very well suited to contain only a time. If you do this, it will be parsed as 01-01-1970 with the specified time. So 18:01:23 becomes 01-01-1970, 18:01:23 and 00:16:23 becomes 01-01-1970, 00:16:23. You probably wanted to compare 18:01:23 to 00:16:23 the next day.
Try something like this:
String actual = "18:01:23";
String limit = "00:16:23";
String[] parts = actual.split(":");
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parts[0]));
cal1.set(Calendar.MINUTE, Integer.parseInt(parts[1]));
cal1.set(Calendar.SECOND, Integer.parseInt(parts[2]));
parts = limit.split(":");
Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parts[0]));
cal2.set(Calendar.MINUTE, Integer.parseInt(parts[1]));
cal2.set(Calendar.SECOND, Integer.parseInt(parts[2]));
// Add 1 day because you mean 00:16:23 the next day
cal2.add(Calendar.DATE, 1);
if (cal1.before(cal2)) {
System.out.println("Not yet at the limit");
}
The library Joda Time is a popular Java date and time library that is much better designed than the standard Java date and calendar API; consider using it if you have to work with dates and times in Java.
With Joda Time you could do this:
String actual = "18:01:23";
String limit = "00:16:23";
DateTimeFormatter df = DateTimeFormat.forPattern("HH:mm:ss");
DateTime ac = df.parseLocalTime(actual).toDateTimeToday();
DateTime lim = df.parseLocalTime(limit).toDateTimeToday().plusDays(1);
if (ac.isBefore(lim)) {
System.out.println("Not yet at the limit");
}
As a quick and dirty solution:
final DateFormat datos = new SimpleDateFormat("HH:mm:ss");
Date ac;
final Date lim = new Date();
String actual, limit;
actual = "18:01:23";
limit = "00:16:23";
try {
ac = datos.parse(actual);
lim.setTime(ac.getTime() + TimeUnit.MINUTES.toMillis(16) + TimeUnit.SECONDS.toMillis(23));
if ( ac.before(lim) ) {
// TODO
}
} catch ( final ParseException e ) {
e.printStackTrace();
}
java.util.Date gets stored as 2010-09-03 15:33:22.246 when the SQL data type is timestamp, how do I set the sub seconds to zero (e.g. 246 in this case) prior to storing the record.
The simplest way would be something like:
long time = date.getTime();
date.setTime((time / 1000) * 1000);
In other words, clear out the last three digits of the "millis since 1970 UTC".
I believe that will also clear the nanoseconds part if it's a java.sql.Timestamp.
Here is an idea:
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("S");
Date d = new Date();
System.out.println(df.format(d));
Calendar c = Calendar.getInstance();
c.set(Calendar.MILLISECOND, 0);
d.setTime(c.getTimeInMillis());
System.out.println(df.format(d));
}
java.util.Calendar can help you.
Calendar instance = Calendar.getInstance();
instance.setTime(date);
instance.clear(Calendar.SECOND);
date = instance.getTime();
Here is another way by java 8 Instant api
LocalDateTime now = LocalDateTime.now();
Instant instant = now.atZone(ZoneId.systemDefault()).toInstant().truncatedTo(ChronoUnit.SECONDS);
Date date = Date.from(instant);
or
Date now = new Date();
Instant instant = now.toInstant().truncatedTo(ChronoUnit.SECONDS);
Date date = Date.from(instant);
Alternatively, you can use Apache Commons DateUtils, for example:
DateUtils.setMilliseconds(new Date(), 0);