How can I calculate a time difference in Java? - java

I want to subtract two time periods say 16:00:00 from 19:00:00. Is there any Java function for this? The results can be in milliseconds, seconds, or minutes.

Java 8 has a cleaner solution - Instant and Duration
Example:
import java.time.Duration;
import java.time.Instant;
...
Instant start = Instant.now();
//your code
Instant end = Instant.now();
Duration timeElapsed = Duration.between(start, end);
System.out.println("Time taken: "+ timeElapsed.toMillis() +" milliseconds");

String time1 = "16:00:00";
String time2 = "19:00:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
Difference is in milliseconds.
I modified sfaizs post.

To get pretty timing differences, then
// d1, d2 are dates
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");

Java 8
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime1= LocalDateTime.parse("2014-11-25 19:00:00", formatter);
LocalDateTime dateTime2= LocalDateTime.parse("2014-11-25 16:00:00", formatter);
long diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();
long diffInSeconds = java.time.Duration.between(dateTime1, dateTime2).getSeconds();
long diffInMinutes = java.time.Duration.between(dateTime1, dateTime2).toMinutes();

Just like any other language; convert your time periods to a unix timestamp (ie, seconds since the Unix epoch) and then simply subtract.
Then, the resulting seconds should be used as a new unix timestamp and read formatted in whatever format you want.
Ah, give the above poster (genesiss) his due credit, code's always handy ;)
Though, you now have an explanation as well :)

import java.util.Date;
...
Date d1 = new Date();
...
...
Date d2 = new Date();
System.out.println(d2.getTime()-d1.getTime()); //gives the time difference in milliseconds.
System.out.println((d2.getTime()-d1.getTime())/1000); //gives the time difference in seconds.
and, to show in a nicer format, you can use:
DecimalFormat myDecimalFormatter = new DecimalFormat("###,###.###");
System.out.println(myDecimalFormatter.format(((double)d2.getTime()-d1.getTime())/1000));

Besides the most common approach with Period and Duration objects you can widen your knowledge with another way for dealing with time in Java.
Advanced Java 8 libraries.
ChronoUnit for Differences.
ChronoUnit is a great way to determine how far apart two Temporal values are. Temporal includes LocalDate, LocalTime and so on.
LocalTime one = LocalTime.of(5,15);
LocalTime two = LocalTime.of(6,30);
LocalDate date = LocalDate.of(2019, 1, 29);
System.out.println(ChronoUnit.HOURS.between(one, two)); //1
System.out.println(ChronoUnit.MINUTES.between(one, two)); //75
System.out.println(ChronoUnit.MINUTES.between(one, date)); //DateTimeException
First example shows that between truncates rather than rounds.
The second shows how easy it is to count different units.
And the last example reminds us that we should not mess up with dates and times in Java :)

public class timeDifference {
public static void main(String[] args) {
try {
Date startTime = Calendar.getInstance().getTime();
Thread.sleep(10000);
Date endTime = Calendar.getInstance().getTime();
long difference = endTime.getTime() - startTime.getTime();
long differenceSeconds = difference / 1000 % 60;
long differenceMinutes = difference / (60 * 1000) % 60;
long differenceHours = difference / (60 * 60 * 1000) % 24;
long differenceDays = difference / (24 * 60 * 60 * 1000);
System.out.println(differenceDays + " days, ");
System.out.println(differenceHours + " hours, ");
System.out.println(differenceMinutes + " minutes, ");
System.out.println(differenceSeconds + " seconds.");
}
catch (Exception e) {
e.printStackTrace();
}
}
}

I found this cleaner.
Date start = new Date();
//Waiting for 10 seconds
Thread.sleep(10000);
Date end = new Date();
long diff = end.getTime() - start.getTime();
String TimeTaken = String.format("[%s] hours : [%s] mins : [%s] secs",
Long.toString(TimeUnit.MILLISECONDS.toHours(diff)),
TimeUnit.MILLISECONDS.toMinutes(diff),
TimeUnit.MILLISECONDS.toSeconds(diff));
System.out.println(String.format("Time taken %s", TimeTaken));
Output
Time taken [0] hours : [0] mins : [10] secs

The painful way is to convert to millis and do the subtraction and then back to whatever seconds or so you want. The better way is to use JodaTime.

String start = "12:00:00";
String end = "02:05:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(start);
Date date2 = format.parse(end);
long difference = date2.getTime() - date1.getTime();
int minutes = (int) TimeUnit.MILLISECONDS.toMinutes(difference);
if(minutes<0)minutes += 1440;
Now minutes will be the correct duration between two time (in minute).

import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws Exception {
String time1 = "12:00:00";
String time2 = "12:01:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
System.out.println(difference/1000);
}
}
It throws exception handles parsing exceptions.

This can be easily done using Java 8 LocalTime;
String time1 = "16:00:00";
String time2 = "19:00:00";
long seconds = Duration.between(LocalTime.parse(time1), LocalTime.parse(time2)).getSeconds()
Duration also supports toMillis(), toMinutes() which can be used in place of getSeconds() to get milliseconds or minutes

Аlternative option if time from different days is taken, for example: 22:00 and 01:55.
public static long getDiffTime(Date date1, Date date2){
if (date2.getTime() - date1.getTime() < 0) {// if for example date1 = 22:00, date2 = 01:55.
Calendar c = Calendar.getInstance();
c.setTime(date2);
c.add(Calendar.DATE, 1);
date2 = c.getTime();
} //else for example date1 = 01:55, date2 = 03:55.
long ms = date2.getTime() - date1.getTime();
//235 minutes ~ 4 hours for (22:00 -- 01:55).
//120 minutes ~ 2 hours for (01:55 -- 03:55).
return TimeUnit.MINUTES.convert(ms, TimeUnit.MILLISECONDS);
}

Try this:
public String timeDifference8(String startTime, String endTime) {
LocalTime initialTime = LocalTime.parse(startTime);
LocalTime finalTime =LocalTime.parse(endTime);
StringJoiner joiner = new StringJoiner(":");
long hours = initialTime.until( finalTime, ChronoUnit.HOURS);
initialTime = initialTime.plusHours( hours );
long minutes = initialTime.until(finalTime, ChronoUnit.MINUTES);
initialTime = initialTime.plusMinutes( minutes );
long seconds = initialTime.until( finalTime, ChronoUnit.SECONDS);
joiner.add(String.valueOf(hours));
joiner.add(String.valueOf(minutes));
joiner.add(String.valueOf(seconds));
return joiner.toString();
}

import java.sql.*;
class Time3 {
public static void main(String args[]){
String time1 = "01:03:23";
String time2 = "02:32:00";
long difference ;
Time t1 = Time.valueOf(time1);
Time t2 = Time.valueOf(time2);
if(t2.getTime() >= t1.getTime()){
difference = t2.getTime() - t1.getTime() -19800000;
}
else{
difference = t1.getTime() - t2.getTime() -19800000;
}
java.sql.Time time = new java.sql.Time(difference);
System.out.println(time);
}
}

/*
* Total time calculation.
*/
private void getTotalHours() {
try {
// TODO Auto-generated method stub
if (tfTimeIn.getValue() != null && tfTimeOut.getValue() != null) {
Long min1 = tfTimeOut.getMinutesValue();
Long min2 = tfTimeIn.getMinutesValue();
Long hr1 = tfTimeOut.getHoursValue();
Long hr2 = tfTimeIn.getHoursValue();
Long hrsTotal = new Long("0");
Long minTotal = new Long("0");
if ((hr2 - hr1) == 1) {
hrsTotal = (long) 1;
if (min1 != 0 && min2 == 0) {
minTotal = (long) 60 - min1;
} else if (min1 == 0 && min2 != 0) {
minTotal = min2;
} else if (min1 != 0 && min2 != 0) {
minTotal = min2;
Long minOne = (long) 60 - min1;
Long minTwo = min2;
minTotal = minOne + minTwo;
}
if (minTotal >= 60) {
hrsTotal++;
minTotal = minTotal % 60;
}
} else if ((hr2 - hr1) > 0) {
hrsTotal = (hr2 - hr1);
if (min1 != 0 && min2 == 0) {
minTotal = (long) 60 - min1;
} else if (min1 == 0 && min2 != 0) {
minTotal = min2;
} else if (min1 != 0 && min2 != 0) {
minTotal = min2;
Long minOne = (long) 60 - min1;
Long minTwo = min2;
minTotal = minOne + minTwo;
}
if (minTotal >= 60) {
minTotal = minTotal % 60;
}
} else if ((hr2 - hr1) == 0) {
if (min1 != 0 || min2 != 0) {
if (min2 > min1) {
hrsTotal = (long) 0;
minTotal = min2 - min1;
} else {
Notification.show("Enter A Valid Time");
tfTotalTime.setValue("00.00");
}
}
} else {
Notification.show("Enter A Valid Time");
tfTotalTime.setValue("00.00");
}
String hrsTotalString = hrsTotal.toString();
String minTotalString = minTotal.toString();
if (hrsTotalString.trim().length() == 1) {
hrsTotalString = "0" + hrsTotalString;
}
if (minTotalString.trim().length() == 1) {
minTotalString = "0" + minTotalString;
}
tfTotalTime.setValue(hrsTotalString + ":" + minTotalString);
} else {
tfTotalTime.setValue("00.00");
}
}
catch (Exception e) {
e.printStackTrace();
}
}

class TimeCalculator
{
String updateTime;
public TimeCalculator(String time)
{
// Time should be in 24 hours format like 15/06/2016 17:39:20
this.updateTime = time;
}
public String getTimeDifference()
{
String td = null;
// Get Current Time
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date currentDate = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(currentDate);
int c_year = calendar.get(Calendar.YEAR);
int c_month = calendar.get(Calendar.MONTH) + 1;
int c_day = calendar.get(Calendar.DAY_OF_MONTH);
// Get Editing Time
Date edit_date = sdf.parse(updateTime);
Calendar edit_calendar = new GregorianCalendar();
edit_calendar.setTime(edit_date);
int e_year = edit_calendar.get(Calendar.YEAR);
int e_month = edit_calendar.get(Calendar.MONTH) + 1;
int e_day = edit_calendar.get(Calendar.DAY_OF_MONTH);
if(e_year == c_year && e_month == c_month && e_day == c_day)
{
int c_hours = calendar.get(Calendar.HOUR_OF_DAY);
int c_minutes = calendar.get(Calendar.MINUTE);
int c_seconds = calendar.get(Calendar.SECOND);
int e_hours = edit_calendar.get(Calendar.HOUR_OF_DAY);
int e_minutes = edit_calendar.get(Calendar.MINUTE);
int e_seconds = edit_calendar.get(Calendar.SECOND);
if(c_hours == e_hours && c_minutes == e_minutes && c_seconds == e_seconds)
{
td = "just now";
return td;
}
else if(c_hours == e_hours && c_minutes == e_minutes)
{
int d_seconds = c_seconds-e_seconds;
td = String.valueOf(d_seconds);
td = td + " seconds ago";
return td;
}
else if(c_hours == e_hours && c_minutes != e_minutes)
{
int d_minutes = c_minutes-e_minutes;
int d_seconds;
if(c_seconds>e_seconds)
{
d_seconds = c_seconds-e_seconds;
}
else
{
d_seconds = e_seconds-c_seconds;
}
td = "00:" + String.valueOf(d_minutes) + ":" + String.valueOf(d_seconds) + " ago";
return td;
}
else
{
int d_minutes, d_seconds, d_hours;
d_hours = c_hours-e_hours;
if(c_minutes>e_minutes)
{
d_minutes = c_minutes - e_minutes;
}
else
{
d_minutes = e_minutes - c_minutes;
}
if(c_seconds>e_seconds)
{
d_seconds = c_seconds - e_seconds;
}
else
{
d_seconds = e_seconds - c_seconds;
}
td = String.valueOf(d_hours) + ":" + String.valueOf(d_minutes) + ":" + String.valueOf(d_seconds) + " ago";
return td;
}
}
else if(e_year == c_year && e_month == c_month && c_day == e_day+1)
{
td = "yesterday";
return td;
}
else
{
td = updateTime;
return td;
}
}
}

using Instant
Instant start = Instant.parse("2017-10-03T10:15:30.00Z");
Instant end = Instant.parse("2017-10-04T11:35:31.00Z");
long duration = Duration.between(start, end).toMillis();
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)*60;
String time = String.format("%02d hours, %02d min, %02d sec",
TimeUnit.MILLISECONDS.toHours(duration),
TimeUnit.MILLISECONDS.toMinutes(duration) - TimeUnit.MILLISECONDS.toHours(duration) * 60,
TimeUnit.MILLISECONDS.toSeconds(duration) - minutes);
;
System.out.println("time = " + time);

Related

calculate elapsed time and display it in Java

There seems to be no easy answer in stackoverflow for this problem. I simply want to get the difference between two Calendar instances and display in HH:mm:ss.SSS
So far, I have
SimpleDateFormat dateFormat = new
SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Calendar start = Calendar.getInstance();
say("start time:"+dateFormat.format(start.getTime()));
and
Calendar ending = Calendar.getInstance();
say("ending time:"+dateFormat.format(ending.getTime()));
long milli = ending.getTime().getTime()
- start.getTime().getTime();
long sec = milli / 1000; // millisec to sec
say("elapsed time: " + sec + "." + milli );
which does work to display the two times.
start time: 2018-03-02 15:44:41.194
*** program runs ***
ending time:2018-03-02 15:44:41.198
elapsed time: 0.4
But shouldn't it be saying 0.004 seconds?
And PLEASE no JodaTime answers. This shop does not support that.
Instant start = Instant.now();
And
Instant end = Instant.now();
long milli = ChronoUnit.MILLIS.between(start, end);
System.out.format(Locale.ENGLISH, "elapsed time: %.3f%n", milli / 1000.0);
On my computer this printed
elapsed time: 0.004
Formatting with String.format or System.out.format() also works with your way of measuring the milliseconds, of course.
Using Java 9 you can (at least on some computers) have more decimals if you want:
System.out.println("elapsed time: "
+ ChronoUnit.NANOS.between(start, end) / (double) TimeUnit.SECONDS.toNanos(1));
I got
elapsed time: 0.003739
I wrote a little function for you, it returns a number as a string filled with as many "0" as you want.
public String getStringNumber(long number, int displaySize) {
String str = new String();
int length = String.valueOf(number).length();
while (length++ < displaySize)
str += "0";
str += number;
return str;
}
Now you can just replace in your code
say("elapsed time: " + sec + "." + getStringNumber(milli, 4));
I finally arrived on this solution. It is awkward and not very elegant, but it works.
Calendar ending = Calendar.getInstance();
say("ending time:"+dateFormat.format(ending.getTime()));
long milli = ending.getTime().getTime()
- start.getTime().getTime();
long hrs = TimeUnit.MILLISECONDS.toHours(milli) % 24;
long
min = TimeUnit.MILLISECONDS.toMinutes(milli) % 60;
long sec
= TimeUnit.MILLISECONDS.toSeconds(milli) % 60;
long mls = milli % 1000;
String elaps =
String.format("%02d:%02d:%02d.%03d", hrs,
min, sec, mls);
say("Elapsed time: " + elaps);
Here is the explanation: I convert the two Calendar variables to long, and subtract. Then I format the Long to a string in format hh:mm:ss.SSS which is what I wanted in the first place.
Here is the output
ending time:2018-03-05 15:07:17.923
Elapsed time: 00:01:15.964
Okay, so, simply off the top of my head, without trying to perform anything kind of fancy, you could make use of the Java 8 date/time API, which provides the capability to calculate the different between two points in time.
So, taking your input, and running it through the code below, it outputs
2018-03-02T15:44:41.194
2018-03-02T15:44:41.198
0.004
Now, personally, I'd take the concept and simply create a DurationFormatter which could take a Duration and spit out your required format, but the idea here is to give you a jumping point to start from.
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Test {
public static void main(String[] args) {
String startTime = "2018-03-02 15:44:41.194";
String endTime = "2018-03-02 15:44:41.198";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime startDateTime = LocalDateTime.parse(startTime, formatter);
LocalDateTime endDateTime = LocalDateTime.parse(endTime, formatter);
System.out.println(startDateTime);
System.out.println(endDateTime);
Duration duration = Duration.between(startDateTime, endDateTime);
long hours = duration.toHours();
duration = duration.minusHours(hours);
long mins = duration.toMinutes();
duration = duration.minusMinutes(mins);
long secs = duration.getSeconds();
duration = duration.minusSeconds(secs);
long millis = duration.toMillis();
StringBuilder sb = new StringBuilder(12);
if (hours > 0) {
sb.append(pad(hours, 2));
}
if (mins == 0 && sb.length() > 0) {
sb.append(":00");
} else if (mins > 0) {
if (hours > 0) {
sb.append(":");
}
sb.append(pad(mins, 2));
}
if (secs == 0 & sb.length() > 0) {
sb.append(":00");
} else if (secs > 0) {
if (mins > 0) {
sb.append(":");
}
sb.append(pad(secs, 2));
}
if (millis == 0 & sb.length() > 0) {
sb.append(".00");
} else if (millis > 0) {
if (secs > 0 || sb.length() > 0) {
sb.append(".");
} else if (sb.length() == 0) {
sb.append("0.");
}
sb.append(pad(millis, 3));
}
System.out.println(sb.toString());
}
public static String pad(long value, long length) {
return String.format("%0" + length + "d", value);
}
}
Now, if we change the input to something like...
String startTime = "2018-03-02 15:44:41.194";
String endTime = "2018-03-08 15:44:41.198";
It outputs
144:00:00.004
Or if we use
String startTime = "2018-03-02 15:44:41.194";
String endTime = "2018-03-08 15:15:41.198";
It outputs
143:31:00.004
Or
String startTime = "2018-03-02 15:44:41.194";
String endTime = "2018-03-08 15:15:50.198";
It outputs
143:31:09.004
Or
2018-03-02T15:44:41.194
2018-03-02T15:50:41.194
It outputs
06:00.00
... to me, this is where it gets weird, technically it's correct (6 mins), but from the format, it's hard to deduce exactly what it means
This is where I might be tempted to use something more like String.format("%02d:%02d:%02d.%04d", hours, mins, secs, millis) which will output 00:06:00.0000, but that all comes do to you needs. You will need to decide how best to take the raw information and present it based on your needs, but there are a couple of different ideas

customize android Date like twitter and instagram news feed

how can I customize the date format in an android development to be like that of twitter and instagram. What i have below my current code, but I don't like the format it produces like "11 minutes ago" or "34 minutes ago". I prefer the twitter format like "11m" or "34m". Please anyone know how i can format my date like that?
Date createdAt = message.getCreatedAt();//get the date the message was created from parse backend
long now = new Date().getTime();//get current date
String convertedDate = DateUtils.getRelativeTimeSpanString(
createdAt.getTime(), now, DateUtils.SECOND_IN_MILLIS).toString();
mPostMessageTimeLabel.setText(convertedDate); //sets the converted date into the message_item.xml view
Had the same problem. Instead of using a library I figured I could probably write my own version and have it be a little more understandable as to what is happening (and be able to tweak it a bit if needed).
Here is the utility method I made (helpful Log statements for Android users to test it out included):
public static String convertLongDateToAgoString (Long createdDate, Long timeNow){
Long timeElapsed = timeNow - createdDate;
// For logging in Android for testing purposes
/*
Date dateCreatedFriendly = new Date(createdDate);
Log.d("MicroR", "dateCreatedFriendly: " + dateCreatedFriendly.toString());
Log.d("MicroR", "timeNow: " + timeNow.toString());
Log.d("MicroR", "timeElapsed: " + timeElapsed.toString());*/
// Lengths of respective time durations in Long format.
Long oneMin = 60000L;
Long oneHour = 3600000L;
Long oneDay = 86400000L;
Long oneWeek = 604800000L;
String finalString = "0sec";
String unit;
if (timeElapsed < oneMin){
// Convert milliseconds to seconds.
double seconds = (double) ((timeElapsed / 1000));
// Round up
seconds = Math.round(seconds);
// Generate the friendly unit of the ago time
if (seconds == 1) {
unit = "sec";
} else {
unit = "secs";
}
finalString = String.format("%.0f", seconds) + unit;
} else if (timeElapsed < oneHour) {
double minutes = (double) ((timeElapsed / 1000) / 60);
minutes = Math.round(minutes);
if (minutes == 1) {
unit = "min";
} else {
unit = "mins";
}
finalString = String.format("%.0f", minutes) + unit;
} else if (timeElapsed < oneDay) {
double hours = (double) ((timeElapsed / 1000) / 60 / 60);
hours = Math.round(hours);
if (hours == 1) {
unit = "hr";
} else {
unit = "hrs";
}
finalString = String.format("%.0f", hours) + unit;
} else if (timeElapsed < oneWeek) {
double days = (double) ((timeElapsed / 1000) / 60 / 60 / 24);
days = Math.round(days);
if (days == 1) {
unit = "day";
} else {
unit = "days";
}
finalString = String.format("%.0f", days) + unit;
} else if (timeElapsed > oneWeek) {
double weeks = (double) ((timeElapsed / 1000) / 60 / 60 / 24 / 7);
weeks = Math.round(weeks);
if (weeks == 1) {
unit = "week";
} else {
unit = "weeks";
}
finalString = String.format("%.0f", weeks) + unit;
}
return finalString;
}
Usage:
Long createdDate = 1453394736888L; // Your Long
Long timeNow = new Date().getTime();
Log.d("MicroR", convertLongDateToAgoString(createdDate, timeNow));
// Outputs:
// 1min
// 3weeks
// 5hrs
// etc.
Feel free to test this out and let me know if you find any issues!
I might be a bit late, but i write it down for somebody who is looking for a solution.
Using PrettyTime you can obtain formatted dates like "2 months ago" and so on.
To fit your needs you have to feed it with a custom TimeFormat object, there is no need to create a new TimeUnit object since we are formatting normal time units.
To do this just create your TimeFormat object for minutes for example:
public class CustomMinuteTimeFormat implements TimeFormat {
#Override
public String format(Duration duration) {
return Math.abs(duration.getQuantity()) + "m";
}
#Override
public String formatUnrounded(Duration duration) {
return format(duration);
}
#Override
public String decorate(Duration duration, String time) {
return time;
}
#Override
public String decorateUnrounded(Duration duration, String time) {
return time;
}
}
Then Instantiate a new PrettyTime instance and set your formatter.
PrettyTime pretty = new PrettyTime();
//This line of code is very important
pretty.registerUnit(new Minute(), new CustomMinuteTimeFormat());
//Use your PrettyTime object as usual
pretty.format(yourDateObject);
This will output "2m" if time elapsed is 2 minutes.

Convert given time in String format to seconds in Android

Suppose time is given in MM:SS(ex- 02:30) OR HH:MM:SS in String format.how can we convert this time to second.
In your case, using your example you could use something like the following:
String time = "02:30"; //mm:ss
String[] units = time.split(":"); //will break the string up into an array
int minutes = Integer.parseInt(units[0]); //first element
int seconds = Integer.parseInt(units[1]); //second element
int duration = 60 * minutes + seconds; //add up our values
If you want to include hours just modify the code above and multiply hours by 3600 which is the number of seconds in an hour.
public class TimeToSeconds {
// given: mm:ss or hh:mm:ss or hhh:mm:ss, return number of seconds.
// bad input throws NumberFormatException.
// bad includes: "", null, :50, 5:-4
public static long parseTime(String str) throws NumberFormatException {
if (str == null)
throw new NumberFormatException("parseTimeString null str");
if (str.isEmpty())
throw new NumberFormatException("parseTimeString empty str");
int h = 0;
int m, s;
String units[] = str.split(":");
assert (units.length == 2 || units.length == 3);
switch (units.length) {
case 2:
// mm:ss
m = Integer.parseInt(units[0]);
s = Integer.parseInt(units[1]);
break;
case 3:
// hh:mm:ss
h = Integer.parseInt(units[0]);
m = Integer.parseInt(units[1]);
s = Integer.parseInt(units[2]);
break;
default:
throw new NumberFormatException("parseTimeString failed:" + str);
}
if (m<0 || m>60 || s<0 || s>60 || h<0)
throw new NumberFormatException("parseTimeString range error:" + str);
return h * 3600 + m * 60 + s;
}
// given time string (hours:minutes:seconds, or mm:ss, return number of seconds.
public static long parseTimeStringToSeconds(String str) {
try {
return parseTime(str);
} catch (NumberFormatException nfe) {
return 0;
}
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class TimeToSecondsTest {
#Test
public void parseTimeStringToSeconds() {
assertEquals(TimeToSeconds.parseTimeStringToSeconds("1:00"), 60);
assertEquals(TimeToSeconds.parseTimeStringToSeconds("00:55"), 55);
assertEquals(TimeToSeconds.parseTimeStringToSeconds("5:55"), 5 * 60 + 55);
assertEquals(TimeToSeconds.parseTimeStringToSeconds(""), 0);
assertEquals(TimeToSeconds.parseTimeStringToSeconds("6:01:05"), 6 * 3600 + 1*60 + 5);
}
#Test
public void parseTime() {
// make sure all these tests fail.
String fails[] = {null, "", "abc", ":::", "A:B:C", "1:2:3:4", "1:99", "1:99:05", ":50", "-4:32", "-99:-2:4", "2.2:30"};
for (String t: fails)
{
try {
long seconds = TimeToSeconds.parseTime(t);
assertFalse("FAIL: Expected failure:"+t+" got "+seconds, true);
} catch (NumberFormatException nfe)
{
assertNotNull(nfe);
assertTrue(nfe instanceof NumberFormatException);
// expected this nfe.
}
}
}
}
int v = 0;
for (var x: t.split(":")) {
v = v * 60 + new Byte(x);
}
This snippet should support HH:MM:SS (v would result in seconds) or HH:MM (v would be in minutes)
try this
hours = totalSecs / 3600;
minutes = (totalSecs % 3600) / 60;
seconds = totalSecs % 60;
timeString = String.format("%02d",seconds);
private static final String TIME_FORMAT = "hh:mm a";//give whatever format you want.
//Function calling
long timeInMillis = TimeUtils.getCurrentTimeInMillis("04:21 PM");
long seconds = timeInMillis/1000;
//Util Function
public static long getCurrentTimeInMillis(String time) {
SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
// sdf.setTimeZone(TimeZone.getTimeZone("GMT")); //getting exact milliseconds at GMT
// sdf.setTimeZone(TimeZone.getDefault());
Date date = null;
try {
date = sdf.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return date.getTime();
}
I have written an extension function in Kotlin for converting String to seconds
fun String?.converTimeToSeconds(): Int {
if (this.isNullOrEmpty().not()) {
val units = this?.split(":")?.toTypedArray()
if (units?.isNotEmpty() == true && units.size >= 3) {
val hours = units[0].toInt()
val minutes = units[1].toInt()
val seconds = units[2].toInt()
return (3660 * hours) + (60 * minutes) + seconds
}
}
return 0
}

Find the number of months and day between date range

I have a start date and end date in database like below.
start date:01/06/2014 end date:30/06/2014
start date:01/07/2014 end date:30/09/2014
start date:01/10/2014 end date:31/03/2015
if i enter the date range
start date 02/06/2014 end date 01/02/2015
the output has to be.
28 days, in 1st slab date range
2 months, 29 days, in 2nd slab date range
4 months in 3rd slab date range
how to achieve this in java.
Thanks in advance.
This question is difficult to answer accurately. I believe this is what you really want,
// get the minimum of any number of dates.
private static Date getMinimum(Date... dates) {
if (dates == null)
return null;
Date min = dates[0];
for (Date d : dates) {
if (d.compareTo(min) < 0) {
min = d;
}
}
return min;
}
// get the maximum of any number of dates.
private static Date getMaximum(Date... dates) {
if (dates == null)
return null;
Date max = dates[0];
for (Date d : dates) {
if (d.compareTo(max) > 0) {
max = d;
}
}
return max;
}
public static String getDateDiff(Date startDate,
Date endDate) {
StringBuilder sb = new StringBuilder();
Calendar start = Calendar.getInstance();
start.setTime(getMinimum(startDate, endDate));
Calendar end = Calendar.getInstance();
end.setTime(getMaximum(startDate, endDate));
if (start.compareTo(end) < 0) {
int monthCount = 0;
int dayCount = 0;
while (start.compareTo(end) < 0) {
start.add(Calendar.MONTH, 1);
if (start.compareTo(end) < 0) {
monthCount++;
}
}
start = Calendar.getInstance();
start.setTime(getMinimum(startDate, endDate));
start.add(Calendar.MONTH, monthCount);
while (start.compareTo(end) < 0) {
start.add(Calendar.DAY_OF_MONTH, 1);
if (start.compareTo(end) < 0) {
dayCount++;
}
}
if (monthCount > 0) {
sb.append(String.format("%d months",
monthCount));
}
if (dayCount > 0) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(String.format("%d days", dayCount));
}
} else {
sb.append("0 days");
}
return sb.toString();
}
public static void main(String[] args) {
String[] input = { "01/06/2014-30/06/2014", //
"01/07/2014-30/09/2014", //
"01/10/2014-31/03/2015", //
"02/06/2014-01/02/2015", };
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
for (String str : input) {
String sArr[] = str.split("-");
try {
Date start = df.parse(sArr[0]);
Date end = df.parse(sArr[1]);
System.out.printf("start: %s, end: %s - diff: %s\n", sArr[0],
sArr[1], getDateDiff(start, end));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
The output is
start: 01/06/2014, end: 30/06/2014 - diff: 28 days
start: 01/07/2014, end: 30/09/2014 - diff: 2 months, 28 days
start: 01/10/2014, end: 31/03/2015 - diff: 5 months, 29 days
start: 02/06/2014, end: 01/02/2015 - diff: 7 months, 29 days
Please check whether below code is helpful. I am using this.
public String getDifference(Date date1, Date date2){
long difference = date2.getTime() - date1.getTime();
long diffDays = difference / (24 * 60 * 60 * 1000);
return (diffDays/30)+" months and "+(diffDays%30)+" days";
}
public int monthsBetweenDates(Date startDate, Date endDate){
Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);
int monthsBetween = 0;
int dateDiff = end.get(Calendar.DAY_OF_MONTH)-start.get(Calendar.DAY_OF_MONTH);
if(dateDiff<0) {
int borrrow = end.getActualMaximum(Calendar.DAY_OF_MONTH);
dateDiff = (end.get(Calendar.DAY_OF_MONTH)+borrrow)-start.get(Calendar.DAY_OF_MONTH);
monthsBetween--;
if(dateDiff>0) {
monthsBetween++;
}
}
else {
monthsBetween++;
}
monthsBetween += end.get(Calendar.MONTH)-start.get(Calendar.MONTH);
monthsBetween += (end.get(Calendar.YEAR)-start.get(Calendar.YEAR))*12;
return monthsBetween;
}

How to get time in 12hr format from a long value in java

I have a long value which have values as given bellow,
e.g.
timeInLong = 1000 (which means 10:00 AM)
timeInLong = 1337 (which means 01:37 PM)
I need a smart way to convert above types of values and get time as 10:00AM and 01:37PM in string format.
Can someone please tell me how to do this?
Code -
Long timeInLong = 1000l;
SimpleDateFormat dateFormat = new SimpleDateFormat("HHmm");
Date date = dateFormat.parse(Long.toString(timeInLong));
System.out.println(new SimpleDateFormat("hh:mm a").format(date));
Result -
10:00 AM
Try:
SimpleDateFormat readerFormat = "HHmm";
SimpleDateFormat writerFormat = "hh:mma";
Date date = readerFormat.parse(Long.toString(timeInLong));
String toPrint = writerFormat.format(date);
I would do something like this:
SimpleDateFormat formatA = new SimpleDateFormat("hhmm");
SimpleDateFormat formatB = new SimpleDateFormat("hh:mm a");
Date intermediate = formatA.parse(String.valueOf(1337));
String result = formatB.format(intermediate);
int timeInLong = 1337;
Calendar c = Calendar.getInstance();
c.set(Calendar.MINUTE, timeInLong % 100);
c.set(Calendar.HOUR_OF_DAY, timeInLong / 100);
System.out.println(new SimpleDateFormat("HH:mm a", Locale.US).format(c.getTime()));
Alternative and efficient oneliner if you want to avoid the SimpleDateFormat import:
String toTimeString(long time) {
return ((time < 1300) ? time / 100 : time / 100 - 12)
+ ":" + time % 100
+ ((time < 1200) ? " AM" : " PM");
}
It seams too easy, but what about:
int hours = timeInLong / 100;
int minutes = timeInLong % 100;
boolean isPM = false;
if (hours > 12) {
isPM = true
}
if (hours > 13) {
hours -= 12;
}
String result = String.format("%02d:%02d %s", hours, minutes, (isPM ? "PM" : "AM"));
Did I miss something?

Categories

Resources