Calculate Rate per hour based on Time - java

import java.text.SimpleDateFormat;
import java.util.Date;
public class Rate_Per_Hour {
public static void main(String[] args) {
String TimeStart = "09.30.00 am";
String TimeEnd= "10.10.00 am";
SimpleDateFormat format = new SimpleDateFormat("hh.mm.ss a");
int total=0;
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(TimeStart);
d2 = format.parse(TimeEnd);
long diff = d2.getTime() - d1.getTime();
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffMinutes = diff / (60 * 1000) % 60;
if (diffMinutes <= 30) {
total = 20;
}
else if (diffHours <=1){
total = 35;
}
System.out.println("Rs." +total);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want output like this:
(Fixed rate per hour for this is Rs.35 )
For 30 min = Rs.20
For 40 min = Rs.25 and so on......
For 1 hour = Rs.35
For 1 hour 10 min = Rs.40
Please help me, figure out how I can do this.

Since the rate increases by 5 every 10 minutes, so just use a simple function to return the rate:
public double rate(int minutes)
{
return 20 + 5*((minutes - 30)/10);
}
Calculate the number of minutes and then pass it as an argument in that function to get the rate. Also, try to keep your code as short as possible but at the same time, simple.

if you need something more flexible rather than fixed rate you could implement an enum with predefined stops
you could define any rate you want for a given time.
for example if long running tasks shall gain higher rates (from your question it was not obvious to me if this rate shall be just the calculated value as in Manish Kundu's answer or if other values might get assigned.)
with this code you could assign higher rates for long running jobs (for example in computer games, jobs that are harder to achieve you return a higher rate or you lower the rate because the player took too much time...)
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class TimeMain {
private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh.mm.ss[ ]a");
public enum Rate {
STOP0(0, 0, 0), // default
STOP1(0, 30, 20), // 30 mins -> Rs.20
STOP2(0, 40, 25), // 40 mins -> Rs.25
STOP3(1, 0, 35), // 1 hour -> Rs.35
STOP4(1, 10, 40); // 1 hour 10 minutes -> Rs.40
int minutes = 0;
int rate = 0;
/*
* hours is actually not needed as 1h10 = 70mins...
*/
private Rate(int hours, int minutes, int rate) {
this.minutes = minutes + hours * 60;
this.rate = rate;
}
public static Rate from(String timeStart, String timeEnd) {
LocalTime time1 = LocalTime.parse(timeStart.toUpperCase(), dateTimeFormatter);
LocalTime time2 = LocalTime.parse(timeEnd.toUpperCase(), dateTimeFormatter);
long minutesBetween = ChronoUnit.MINUTES.between(time1, time2);
for (int i = 0; i < Rate.values().length; i++) {
Rate r = Rate.values()[i];
if (r.minutes > minutesBetween) {
return Rate.values()[i-1];
}
}
return STOP0;
}
public String toString() {
return String.format("Rs.%s", rate);
}
}
public static void main(String... args) {
String timeStart = "09.30.00 am";
String timeEnd = "10.10.00 am";
System.out.println(Rate.from(timeStart, timeEnd));
}
}

Related

Get total hours and minutes from 10 values

I have list of decimal values like...
1.30
1.00
1.50
2.50
2.10
I want to calculate total hours and minutes from this list.
can you please help me how to do it ?
I want this in java.
May be this can help you :
public class TimeCalculator {
public static void main(String[] args) {
long sumOfMilliSeconds = 0;
double array[] = new double[] {
1.30, 1.00, 1.50, 2.50, 2.10
};
for (double d : array) {
sumOfMilliSeconds = sumOfMilliSeconds + convertToMilliSecounds(d);
}
convertDateformat(sumOfMilliSeconds);
}
public static void convertDateformat(long milliSeconds) {
Date date = new Date(milliSeconds);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(date));
}
public static long convertToMilliSecounds(double taktTime) {
long timeInMilliSeconds = (long) (taktTime * 60 * 1000);
return timeInMilliSeconds;
}
}

time conversion in JAVA with formula

What I want to do?
I want to return time and display based on user's input. Say, user enters in console starthour: 23 startminute: 45 duration (in min): 30 then the period for start time will be PM offcourse and you can see below I calculated the start time based on the above things, but issue is calculating the endtime. For example, in the above start times, the end time should become 00:15 with the period AM and not PM like start hour.
What I did?
public String toString(){
int h = (getHour()==0 || getHour()==12) ? getHour() : getHour()%12;
String period = (getHour()<12)? "AM" : "PM";
return String.format("%02d:%02d %s", h, getMinute(), period);
}
What to do?
The above formula calculates the start time and its period, correctly, but I need a similar formula that can calculate the endhour correctly based on start hour, start minutes and duration entered by the user.
Basically, above mentioned code needs to be manipulated to figure out the endhour, endminute and its period.
Note: Please don't tell about local time use for getting end time and period. Thankyou
EDIT: Here is what I did now:
public String toString(){
int endh = (getEndHour()==0 || getEndHour()==12) ? getEndHour() : getEndHour()%12;
String period = ((getEndHour() + duration) <12)? "AM" : "PM";
return String.format("%02d:%02d %s", endh, getEndHour(), period);
}
you should use 60 modulo for simplicity. here it is
public class Timer {
int hour;
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public void addDuration(int duration) {
hour = hour + (minutes + duration)/ 60;
minutes = (minutes + duration) % 60;
}
int minutes;
#Override
public String toString() {
int h = (getHour() == 0 || getHour() == 12) ? getHour()
: getHour() % 24;
String period = (getHour() < 12) ? "AM" : "PM";
return String.format("%02d:%02d %s", h, getMinutes(), period);
}
public static void main(String args[]) {
Timer time = new Timer();
time.setHour(23);
time.setMinutes(45);
System.out.println(time.getHour());
time.addDuration(30);
System.out.println(time.getHour());
System.out.println(time);
}
}

Java representing time class

I want to represent time with my time class. I can't use get and set methods.Only I can use listed methods on the code.But it doesn't work.
It returns 0:0:0.
public int addHours(int hours)
{
if(hours>=0&&hours<=23)
{
return hours;
}
return 0;
}
public int addMinutes(int minutes)
{
if(minutes>=0&&minutes<=59)
{
return minutes;
}
return 0;
}
public int addSeconds(int seconds)
{
if(seconds>=0&&seconds<=59)
{
return seconds;
}
return 0;
}
public String showTime()
{
return hours+":"+minutes+":"+seconds;
}
}
your code does nothing.
you need to do something like this:
public void addHours( int hours ){
this.hours += hours; // add hours
this.hours %= 24; // roll over at 24 hours
}
public void addMinutes( int minutes ){
this.minutes += minutes; // add minutes
addHours(this.minutes/60); // carry over to hours
this.minutes %= 60; // roll over at 60 minutes
}
public void addSeconds( int seconds ){
this.seconds += seconds; // add seconds
addMinutes(seconds/60); // carry over to minutes
this.seconds %= 60; // roll over at 60 seconds
}
(it probably won't matter, but this is not thread safe at all)
but this is generally a bad idea. Java 8 has a beautiful time api, pre Java-8 there is the JodaTime library (which is actually the basis of the Java 8 time api). It seems what you want to do could benefit from LocalTime:
LocalTime t = LocalTime.of(13,50,27).addHours(1).addMinutes(1).addSeconds(1);
System.out.println(t.toString());
// prints 14:51:28
Use java.util.Calendar and java.text.SimpleDateFormat:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 0);
cal.add(Calendar.HOUR, 5);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(cal.getTime()));

Calculating time between datetimes

Let's say I have two datetimes, 30-11-2015 10:00 and 02-12-2015 15:00. I also have two times, 07:00 and 22:00. How could I calculate the amount of time passed between the two date/times that was within the second times? Using Calendar object? It seems simple but its boggling my mind.
Since none of the other answers include runnable code, I can't tell if they solve the problem or not.
To calculate the duration of a time range within a date range, you have to:
Split the date range into multiple date ranges, each spanning no more than one day.
Calculate the time range within each day date range
Taking the example date range from the question. 30-11-2015 10:00 and 02-12-2015 15:00, we generate the following split day date ranges:
30-11-2015 10:00 - 30-11-2015 24:00
01-12-2015 00:00 - 01-12-2015 24:00
02-12-2015 00:00 - 02-12-2015 15:00
Now, we can apply the time range of 7:00 - 22:00 to each of the split day date ranges.
30-11-2015 10:00 - 30-11-2015 24:00 -> 12 hours
01-12-2015 00:00 - 01-12-2015 24:00 -> 15 hours
02-12-2015 00:00 - 02-12-2015 15:00 -> 8 hours
For a total of 35 hours. The actual calculation would probably be in minutes instead of hours.
Edited to add: I created a Time and a TimeRange class to hold the time and a day time range, respectively. I used the java.util.Date, although I had to create my own increment a day method.
I put all of the classes together so I could post this easier. The classes should be put in separate files.
package com.ggl.testing;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TimeRangeTest {
private static final SimpleDateFormat inputDateFormat = new SimpleDateFormat(
"dd-MM-yyyy");
public static void main(String[] args) {
TimeRangeTest test = new TimeRangeTest();
int minutes = test.calculateTotalMinutes("30-11-2015 10:00",
"02-12-2015 15:00", "07:00", "22:00");
System.out.println(minutes + " minutes, " + (minutes / 60) + " hours");
}
public int calculateTotalMinutes(String startDateTimeString,
String endDateTimeString, String startTimeString,
String endTimeString) {
try {
List<TimeRange> timeRanges = generateTimeRanges(
startDateTimeString, endDateTimeString);
return calculateTimeRange(timeRanges, startTimeString,
endTimeString);
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
private List<TimeRange> generateTimeRanges(String startDateTimeString,
String endDateTimeString) throws ParseException {
Date startDate = inputDateFormat.parse(startDateTimeString.substring(0,
10));
Time startTime = new Time(startDateTimeString.substring(11));
Date endDate = inputDateFormat
.parse(endDateTimeString.substring(0, 10));
Time endTime = new Time(endDateTimeString.substring(11));
List<TimeRange> timeRanges = new ArrayList<>();
Date currentDate = new Date(startDate.getTime());
Time currentTime = new Time(startTime);
Time eodTime = new Time("24:00");
while (currentDate.compareTo(endDate) < 0) {
TimeRange timeRange = new TimeRange(currentDate, currentTime,
eodTime);
timeRanges.add(timeRange);
currentTime = new Time("00:00");
currentDate = new Date(currentDate.getTime() + 24L * 60L * 60L
* 1000L);
}
TimeRange timeRange = new TimeRange(currentDate, currentTime, endTime);
timeRanges.add(timeRange);
return timeRanges;
}
private int calculateTimeRange(List<TimeRange> timeRanges,
String startTimeString, String endTimeString) {
int count = 0;
Time startTime = new Time(startTimeString);
Time endTime = new Time(endTimeString);
for (TimeRange timeRange : timeRanges) {
Time sodTime = new Time(timeRange.getStartTime());
Time eodTime = new Time(timeRange.getEndTime());
Time sTime = startTime.max(sodTime);
Time eTime = endTime.min(eodTime);
count += eTime.difference(sTime);
}
return count;
}
public class TimeRange {
private final SimpleDateFormat inputDateFormat = new SimpleDateFormat(
"dd-MM-yyyy");
private final Date date;
private final Time startTime;
private final Time endTime;
public TimeRange(Date date, Time startTime, Time endTime) {
this.date = date;
this.startTime = startTime;
this.endTime = endTime;
}
public Date getDate() {
return date;
}
public Time getStartTime() {
return startTime;
}
public Time getEndTime() {
return endTime;
}
#Override
public String toString() {
return inputDateFormat.format(getDate()) + " "
+ startTime.toString() + " -> " + endTime.toString();
}
}
public class Time {
private final int minutesPastMidnight;
public Time(String timeString) {
int hours = Integer.valueOf(timeString.substring(0, 2));
int minutes = Integer.valueOf(timeString.substring(3, 5));
this.minutesPastMidnight = hours * 60 + minutes;
}
public Time(Time time) {
this.minutesPastMidnight = time.getMinutesPastMidnight();
}
private int getMinutesPastMidnight() {
return minutesPastMidnight;
}
public int difference(Time time) {
return this.getMinutesPastMidnight()
- time.getMinutesPastMidnight();
}
public Time min(Time time) {
return (difference(time) > 0) ? time : this;
}
public Time max(Time time) {
return (difference(time) > 0) ? this : time;
}
#Override
public String toString() {
int hours = minutesPastMidnight / 60;
int minutes = minutesPastMidnight - (hours * 60);
return String.format("%02d:%02d", hours, minutes);
}
}
}
If you use java8, you can use LocalDateTime. Then your code could looks like this:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTimeStart = LocalDateTime.parse("2015-10-01 10:00", formatter);
LocalDateTime dateTimeEnd = LocalDateTime.parse("2015-10-02 10:00", formatter);
long seconds = Duration.between(dateTimeStart, dateTimeEnd).getSeconds();
Or LocalTime if you have only time. Then it could looks like this:
LocalTime timeStart = LocalTime.parse("07:00");
LocalTime timeEnd = LocalTime.parse("22:00");
long seconds = Duration.between(timeStart, timeEnd).getSeconds();
If you can't use java8, you can get the number of milliseconds since 1970-01-01 00:00:00 to your date using getTime() method and do simple subtraction operation, like this:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date dateStart = simpleDateFormat.parse("2015-10-01 10:00");
Date dateEnd = simpleDateFormat.parse("2015-10-02 10:00");
long milliseconds = dateEnd.getTime() - dateStart.getTime();
long seconds = resultInMillisecond / 1000;

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.

Categories

Resources