JasperSoft Studio - How is the best way to to print a period of time (minutes) as hh:mm? [duplicate] - jasper-reports

I need to convert minutes to hours and minutes in java. For example 260 minutes should be 4:20. can anyone help me how to do convert it.

If your time is in a variable called t
int hours = t / 60; //since both are ints, you get an int
int minutes = t % 60;
System.out.printf("%d:%02d", hours, minutes);
It couldn't get easier
Addendum from 2021:
Please notice that this answer is about the literal meaning of the question: how to convert an amount of minute to hours + minutes. It has nothing to do with time, time zones, AM/PM...
If you need better control about this kind of stuff, i.e. you're dealing with moments in time and not just an amount of minutes and hours, see Basil Bourque's answer below.

tl;dr
Duration.ofMinutes( 260L )
.toString()
PT4H20M
… or …
LocalTime.MIN.plus(
Duration.ofMinutes( 260L )
).toString()
04:20
Duration
The java.time classes include a pair of classes to represent spans of time. The Duration class is for hours-minutes-seconds, and Period is for years-months-days.
Duration d = Duration.ofMinutes( 260L );
Duration parts
Access each part of the Duration by calling to…Part. These methods were added in Java 9 and later.
long days = d.toDaysPart() ;
int hours = d.toHoursPart() ;
int minutes = d.toMinutesPart() ;
int seconds = d.toSecondsPart() ;
int nanos = d.toNanosPart() ;
You can then assemble your own string from those parts.
ISO 8601
The ISO 8601 standard defines textual formats for date-time values. For spans of time unattached to the timeline, the standard format is PnYnMnDTnHnMnS. The P marks the beginning, and the T separates the years-month-days from the hours-minutes-seconds. So an hour and a half is PT1H30M.
The java.time classes use ISO 8601 formats by default for parsing and generating strings. The Duration and Period classes use this particular standard format. So simply call toString.
String output = d.toString();
PT4H20M
For alternate formatting, build your own String in Java 9 and later (not in Java 8) with the Duration::to…Part methods. Or see this Answer for using regex to manipulate the ISO 8601 formatted string.
LocalTime
I strongly suggest using the standard ISO 8601 format instead of the extremely ambiguous and confusing clock format of 04:20. But if you insist, you can get this effect by hacking with the LocalTime class. This works if your duration is not over 24 hours.
LocalTime hackUseOfClockAsDuration = LocalTime.MIN.plus( d );
String output = hackUseOfClockAsDuration.toString();
04:20
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Use java.text.SimpleDateFormat to convert minute into hours and minute
SimpleDateFormat sdf = new SimpleDateFormat("mm");
try {
Date dt = sdf.parse("90");
sdf = new SimpleDateFormat("HH:mm");
System.out.println(sdf.format(dt));
} catch (ParseException e) {
e.printStackTrace();
}

You can also use the TimeUnit class. You could define private static final String FORMAT = "%02d:%02d:%02d";
can have a method like:
public static String parseTime(long milliseconds) {
return String.format(FORMAT,
TimeUnit.MILLISECONDS.toHours(milliseconds),
TimeUnit.MILLISECONDS.toMinutes(milliseconds) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(milliseconds)),
TimeUnit.MILLISECONDS.toSeconds(milliseconds) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(milliseconds)));
}

I use this function for my projects:
public static String minuteToTime(int minute) {
int hour = minute / 60;
minute %= 60;
String p = "AM";
if (hour >= 12) {
hour %= 12;
p = "PM";
}
if (hour == 0) {
hour = 12;
}
return (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute) + " " + p;
}

It can be done like this
int totalMinutesInt = Integer.valueOf(totalMinutes.toString());
int hours = totalMinutesInt / 60;
int hoursToDisplay = hours;
if (hours > 12) {
hoursToDisplay = hoursToDisplay - 12;
}
int minutesToDisplay = totalMinutesInt - (hours * 60);
String minToDisplay = null;
if(minutesToDisplay == 0 ) minToDisplay = "00";
else if( minutesToDisplay < 10 ) minToDisplay = "0" + minutesToDisplay ;
else minToDisplay = "" + minutesToDisplay ;
String displayValue = hoursToDisplay + ":" + minToDisplay;
if (hours < 12)
displayValue = displayValue + " AM";
else
displayValue = displayValue + " PM";
return displayValue;
} catch (Exception e) {
LOGGER.error("Error while converting currency.");
}
return totalMinutes.toString();

(In Kotlin) If you are going to put the answer into a TextView or something you can instead use a string resource:
<string name="time">%02d:%02d</string>
And then you can use this String resource to then set the text at run time using:
private fun setTime(time: Int) {
val hour = time / 60
val min = time % 60
main_time.text = getString(R.string.time, hour, min)
}

Given input in seconds you can transform to format hh:mm:ss like this :
int hours;
int minutes;
int seconds;
int formatHelper;
int input;
//formatHelper maximum value is 24 hours represented in seconds
formatHelper = input % (24*60*60);
//for example let's say format helper is 7500 seconds
hours = formatHelper/60*60;
minutes = formatHelper/60%60;
seconds = formatHelper%60;
//now operations above will give you result = 2hours : 5 minutes : 0 seconds;
I have used formatHelper since the input can be more then 86 400 seconds, which is 24 hours.
If you want total time of your input represented by hh:mm:ss, you can just avoid formatHelper.
I hope it helps.

Here is my function for convert a second,millisecond to day,hour,minute,second
public static String millisecondToFullTime(long millisecond) {
return timeUnitToFullTime(millisecond, TimeUnit.MILLISECONDS);
}
public static String secondToFullTime(long second) {
return timeUnitToFullTime(second, TimeUnit.SECONDS);
}
public static String timeUnitToFullTime(long time, TimeUnit timeUnit) {
long day = timeUnit.toDays(time);
long hour = timeUnit.toHours(time) % 24;
long minute = timeUnit.toMinutes(time) % 60;
long second = timeUnit.toSeconds(time) % 60;
if (day > 0) {
return String.format("%dday %02d:%02d:%02d", day, hour, minute, second);
} else if (hour > 0) {
return String.format("%d:%02d:%02d", hour, minute, second);
} else if (minute > 0) {
return String.format("%d:%02d", minute, second);
} else {
return String.format("%02d", second);
}
}
Testing
public static void main(String[] args) {
System.out.println("60 => " + secondToFullTime(60));
System.out.println("101 => " + secondToFullTime(101));
System.out.println("601 => " + secondToFullTime(601));
System.out.println("7601 => " + secondToFullTime(7601));
System.out.println("36001 => " + secondToFullTime(36001));
System.out.println("86401 => " + secondToFullTime(86401));
}
Output
60 => 1:00
101 => 1:41
601 => 10:01
7601 => 2:06:41
36001 => 10:00:01
86401 => 1day 00:00:01
Hope it help

Minutes mod 60 will gives hours with minutes remaining.
http://www.cafeaulait.org/course/week2/15.html

int mHours = t / 60; //since both are ints, you get an int
int mMinutes = t % 60;
System.out.printf("%d:%02d", "" +mHours, "" +mMinutes);

Solution on kotlin Documentation
import kotlin.time.Duration
import kotlin.time.DurationUnit
import kotlin.time.toDuration
val min = 150.toDuration(DurationUnit.MINUTES)
val time = min.toComponents { days, hours, minutes, seconds, nanoseconds ->
"$days $hours $minutes $seconds $nanoseconds"
}
We get 0 days 2 hours 30 minutes 0 seconds 0 nanoseconds
We can also use
DurationUnit.DAYS
DurationUnit.HOURS
DurationUnit.SECONDS
DurationUnit.MILLISECONDS
DurationUnit.MICROSECONDS
DurationUnit.NANOSECONDS

long d1Ms=asa.getTime();
long d2Ms=asa2.getTime();
long minute = Math.abs((d1Ms-d2Ms)/60000);
int Hours = (int)minute/60;
int Minutes = (int)minute%60;
stUr.setText(Hours+":"+Minutes);

Try this code:
import java.util.Scanner;
public class BasicElement {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int hours;
System.out.print("Enter the hours to convert:");
hours =input.nextInt();
int d=hours/24;
int m=hours%24;
System.out.println(d+"days"+" "+m+"hours");
}
}

import java.util.Scanner;
public class Time{
public static void main(String[]args){
int totMins=0;
int hours=0;
int mins=0;
Scanner sc= new Scanner(System.in);
System.out.println("Enter the time in mins: ");
totMins= sc.nextInt();
hours=(int)(totMins/60);
mins =(int)(totMins%60);
System.out.printf("%d:%d",hours,mins);
}
}

Related

How to convert the current time to seconds? in Flutter?

I have two methods, one method with which I get the current time in milliseconds and the second method I get how much time I need to go to the store in seconds. But I need to subtract (current time) - (drive time to the store), for this I need to convert the current time to seconds, tell me how to do this?
here i get the current time
void getTimeNow() {
var ms = (DateTime.now()).millisecondsSinceEpoch;
var time = (ms / 1000).round();
}
here I get the travel time to the shop in seconds
String getTimeToStation (DirectionModel? directionModel) {
double duration = -1;
if (directionModel != null &&
directionModel.routes[0].summary.travelTimeInSeconds != null) {
duration = directionModel.routes[0].summary.travelTimeInSeconds / 60;
}
return duration != -1 ? '${duration.toStringAsFixed(1)} h' : '';
}
You can subtract time like
final currentTime = DateTime.now();
Duration driveTimeToStore = Duration(seconds: 4);
final DateTime driveBeginTime = currentTime.subtract(driveTimeToStore);

Time with flutter

I am totally new with flutter and I do not understand how can I resolve a problem.
I'm actually working to a kart race app and:
I need to read a string like 1:02.456
Convert in some kind of time
Compare with another string similar to first one
Go to do something
es:
blap = null;
if(1:02.456 < 1:03.589){
blap = '1:02.456';
} else {
blap = '1:03.589;
}
I read on the web that I ca use the class DateTime, but every time I try to convert the string in an object of that class, I do not get wat I want.
There is a better way?
Thank you.
If you are working on a kart race app probably you need to use Duration, not DateTime.
This is one way to convert a string like yours into Duration
Duration parseDuration(String s) {
int hours = 0;
int minutes = 0;
int micros;
List<String> parts = s.split(':');
if (parts.length > 2) {
hours = int.parse(parts[parts.length - 3]);
}
if (parts.length > 1) {
minutes = int.parse(parts[parts.length - 2]);
}
micros = (double.parse(parts[parts.length - 1]) * 1000000).round();
return Duration(hours: hours, minutes: minutes, microseconds: micros);
}
Then, to compare two Duration in the way you wanted, this is an example:
String blap;
Duration time1=Duration(hours: 1),time2=Duration(hours: 2);
if(time1.compareTo(time2)<0){
//time2 is greater than time1
blap=time1.toString();
}else{
blap=time2.toString();
}

Flutter how to subtract time from other time

I have 2 times which I need to do subtract and I am almost close but there is one big issue
I have 2 times in string-like 10:00AM and 10:00PM
And my code is this
var df = DateFormat("hh:mm");
var durationStart = DateFormat('HH:mm').format(df.parse(10:00AM));
var durationEnd = DateFormat('HH:mm').format(df.parse(10:00PM));
print('durationStart ${durationStart}');
print('durationEnd ${durationEnd}');
var Startparts = durationStart.split(':');
var startDurationSet = Duration(hours: int.parse(Startparts[0].trim()), minutes: int.parse(Startparts[1].trim()));
var Endparts = durationEnd.split(':');
var endDurationSet = Duration(hours: int.parse(Endparts[0].trim()), minutes: int.parse(Endparts[1].trim()));
print('startDurationSet ${startDurationSet}');
var result = Duration(hours: int.parse(Endparts[0].trim()) - int.parse(Startparts[0].trim()) , minutes: int.parse(Startparts[1].trim()) - int.parse(Endparts[1].trim()));
print('result ${result.toString().replaceAll('-', '')}');
So I have 2 times one is startTime and one is End time. I simply need a difference between hours. for example, I have 10:00Am and 01:00PM i need 3hours but it's showing 9hours. But what I am receiving is if I have 10:00AM and 10:00pm it's showing 0 hours but its needs to show 12. Same
It is easy if you can get your start and end date in DateTime properly
Hint, I use "hh:mma" since that is your original format => "10:00AM"
If I use "HH:mm" like you do, i'll always get the same time since it doesn't parse the AM/PM after the 10:00
// Get your time in term of date time
DateTime startDate = DateFormat("hh:mma").parse("10:00AM");
DateTime endDate = DateFormat("hh:mma").parse("10:00PM");
// Get the Duration using the diferrence method
Duration dif = endDate.difference(startDate);
// Print the result in any format you want
print(dif.toString(); // 12:00:00.000000
print(dif.inHours); // 12
Are you looking for something like this?
TimeOfDay _calcTimeOfDay(int hour, int minute) {
if (minute > 60) {
minute = (minute % 60);
hour += 1;
}
return TimeOfDay(hour: hour, minute: minute);
}
The problem is if you have hour=24 and minute=75 then the hour would be 25, which is not a valid hour.
Not sure I fully understand the question, maybe if you can provide more info.
What you need to add on your DateFormat is the code for am/pm marker: a. Using either format hh:mma or h:ma should work.
You can then use DateTime.difference() to calculate the time variance from durationStart and durationEnd. Here's a sample that you can run on DartPad.
import 'package:intl/intl.dart';
void main() {
/// Set the format that of the Date/Time that like to parse
/// h - 12h in am/pm
/// m - minute in hour
/// a - am/pm marker
/// See more format here: https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html
var dateFormat = DateFormat('h:ma');
DateTime durationStart = dateFormat.parse('10:00AM');
DateTime durationEnd = dateFormat.parse('10:00PM');
print('durationStart: $durationStart');
print('durationEnd: $durationEnd');
/// Fetch the difference using DateTime.difference()
/// https://api.flutter.dev/flutter/dart-core/DateTime/difference.html
print('difference: ${durationEnd.difference(durationStart).inHours}');
}
Use package
intl: ^0.17.0
import 'package:intl/intl.dart';
var dateFormat = DateFormat('h:ma');
DateTime durationStart = dateFormat.parse('10:00AM');
DateTime durationEnd = dateFormat.parse('1:00PM');
print('durationStart: $durationStart');
print('durationEnd: $durationEnd');
var differenceInHours = durationEnd.difference(durationStart).inHours;
print('difference: $differenceInHours hours');
I have created one class for you:
import 'package:intl/intl.dart';
class DateUtils {
static String getTimeDifference(String startTime, String endTime){
/// Set the format that of the Date/Time that like to parse
/// h - 12h in am/pm
/// m - minute in hour
/// a - am/pm marker
/// See more format here: https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html
var dateFormat = DateFormat('h:ma');
DateTime durationStart = dateFormat.parse(startTime);
DateTime durationEnd = dateFormat.parse(endTime);
return '${durationEnd.difference(durationStart).inHours} hours';
}
}
How you can use:
void main() {
print("10:00PM, 10:30PM => " + DateUtils.getTimeDifference("10:00PM", "10:30PM"));
print("12:00AM, 04:00AM => " + DateUtils.getTimeDifference("12:00AM", "04:00AM"));
print("01:00AM, 03:00AM => " + DateUtils.getTimeDifference("01:00AM", "03:00AM"));
print("12:00AM, 06:00PM => " + DateUtils.getTimeDifference("12:00AM", "06:00PM"));
print("04:00PM, 03:00PM => " + DateUtils.getTimeDifference("04:00PM", "03:00PM"));
}
Output:
10:00PM, 10:30PM => 0 hours
12:00AM, 04:00AM => 4 hours
01:00AM, 03:00AM => 2 hours
12:00AM, 06:00PM => 18 hours
04:00PM, 03:00PM => -1 hours
Hope it will be helpful.

How to subtract Hijrah year from a Hijrah Date in Java 8 Date API

I want to display the Ramadan 2017 start and end dates. I tried writing code using the HijrahChronology built into Java 8 and later, with HijrahDate class.
import java.time.LocalDate;
import java.time.chrono.HijrahDate;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAdjusters;
public class Ramdan {
public static void main(String[] args) {
HijrahDate ramdanDate = HijrahDate.now().with(ChronoField.DAY_OF_MONTH, 1).with(ChronoField.MONTH_OF_YEAR, 9);
LocalDate ramdanStart = LocalDate.from(ramdanDate);
LocalDate ramdanEnd = LocalDate.from(ramdanDate.with(TemporalAdjusters.lastDayOfMonth()));
System.out.println("Ramdan 2017");
System.out.println(ramdanStart);
System.out.println(ramdanEnd);
}
}
But it obviously prints out the dates for current year, i.e., 2018.
Output
Ramdan 2017
2018-05-16
2018-06-14
I tried many things like minus years, or doing temporal adjustments but nothing helped. Can someone suggest a cool way of achieving it?
I’m not sure it’s the perfect way to do it, but this works for me and doesn’t seem all too complicated:
ramdanDate = ramdanDate.with(ChronoField.YEAR, ramdanDate.get(ChronoField.YEAR) - 1);
With this line inserted before you convert to LocalDate your code now prints:
Ramdan 2017
2017-05-27
2017-06-24
Edit:
Suppose even if (in case you got a Gregorian year that overlaps with
two instances of Ramadan, finding both) is desired...I cannot think of
a way of achieving it. Can you suggest?
Keep your tongue straight in your mouth:
public static void printRamdanDates(int gregorianYear) {
LocalDate gregDate = LocalDate.ofYearDay(gregorianYear, 1);
HijrahDate ramdanDate = HijrahDate.from(gregDate)
.with(ChronoField.DAY_OF_MONTH, 1)
.with(ChronoField.MONTH_OF_YEAR, 9);
LocalDate ramdanStart = LocalDate.from(ramdanDate);
LocalDate ramdanEnd = LocalDate.from(ramdanDate.with(TemporalAdjusters.lastDayOfMonth()));
// if in previous Gregorian year, skip
while (ramdanEnd.getYear() < gregorianYear) {
ramdanDate = ramdanDate.with(ChronoField.YEAR, ramdanDate.get(ChronoField.YEAR) + 1);
ramdanStart = LocalDate.from(ramdanEnd);
ramdanEnd = LocalDate.from(ramdanDate.with(TemporalAdjusters.lastDayOfMonth()));
}
if (ramdanStart.getYear() > gregorianYear) { // in following Gregorian year
System.out.println("No Ramdan in " + gregorianYear);
} else {
System.out.println("Ramdan " + gregorianYear);
do {
System.out.println(ramdanStart);
System.out.println(ramdanEnd);
ramdanDate = ramdanDate.with(ChronoField.YEAR, ramdanDate.get(ChronoField.YEAR) + 1);
ramdanStart = LocalDate.from(ramdanDate);
ramdanEnd = LocalDate.from(ramdanDate.with(TemporalAdjusters.lastDayOfMonth()));
} while (ramdanStart.getYear() == gregorianYear);
}
}
If I feed 2017 to the above method, it gives the same result as before:
printRamdanDates(2017);
Output:
Ramdan 2017
2017-05-27
2017-06-24
But try, for example, 2000 or 2030 when Ramadan happens twice in the Gregorian/ISO year.
printRamdanDates(2000);
printRamdanDates(2030);
Output:
Ramdan 2000
1999-12-09
2000-01-07
2000-11-27
2000-12-26
Ramdan 2030
2030-01-05
2030-02-03
2030-12-26
2031-01-23

Zend Date -- day difference

I have the below line of codes
$day1 = new Zend_Date('2010-03-01', 'YYYY-mm-dd');
$day2 = new Zend_Date('2010-03-05', 'YYYY-mm-dd');
$dateDiff = $day2->getDate()->get(Zend_Date::TIMESTAMP) - $day1->getDate()->get(Zend_Date::TIMESTAMP);
$days = floor((($dateDiff / 60) / 60) / 24);
return $days;
this will return 4
But if gave
$day1 = new Zend_Date('2010-02-28', 'YYYY-mm-dd');
$day2 = new Zend_Date('2010-03-01', 'YYYY-mm-dd');
$dateDiff = $day2->getDate()->get(Zend_Date::TIMESTAMP) - $day1->getDate()->get(Zend_Date::TIMESTAMP);
$days = floor((($dateDiff / 60) / 60) / 24);
return $days;
it will return -27 .. how will i get right answer
$firstDay = new Zend_Date('2010-02-28', 'YYYY-MM-dd');
$lastDay = new Zend_Date('2010-03-01', 'YYYY-MM-dd');
$diff = $lastDay->sub($firstDay)->toValue();
$days = ceil($diff/60/60/24) +1;
return $days;
this gives the right answer
I believe the problem is in your part string. Try YYYY-MM-dd instead.
$day1 = new Zend_Date('2010-02-28', 'YYYY-MM-dd');
$day2 = new Zend_Date('2010-03-01', 'YYYY-MM-dd');
echo $day2->sub($day1)->toString(Zend_Date::DAY);
$cerimonia = new Zend_Date('your date here');
$days = $cerimonia->sub(Zend_Date::now());
$days = round($days/86400)+1;
I've extended Zend_Date for my own convenience functions. My solution is similar to Nisanth's, with some key differences:
calculate the beginning of the day for both days before comparing
use round() instead of ceil()
do not add 1 to the result
Example code:
class My_Date extends Zend_Date
{
public static function now($locale = null)
{
return new My_Date(time(), self::TIMESTAMP, $locale);
}
/**
* set to the first second of current day
*/
public function setDayStart()
{
return $this->setHour(0)->setMinute(0)->setSecond(0);
}
/**
* get the first second of current day
*/
public function getDayStart()
{
$clone = clone $this;
return $clone->setDayStart();
}
/**
* get count of days between dates, ignores time values
*/
public function getDaysBetween($date)
{
// 86400 seconds/day = 24 hours/day * 60 minutes/hour * 60 seconds/minute
// rounding takes care of time changes
return round($date->getDayStart()->sub(
$this->getDayStart()
)->toValue() / 86400);
}
}
If $date is a Zend_Date object you can use the following:
if ($date->isEarlier(Zend_Date::now()->subDay(2)){
[...]
}
or the other subXxx functions of the Zend_Date object.
number of days between date of registration (later) and date of purchase (before)
// $datePurchase instanceof Zend_Date
// $dateRegistration instanceof Zend_Date
if($datePurchase && $dateRegistration) {
$diff = $dateRegistration->sub($datePurchase)->toValue();
$days = ceil($diff/60/60/24)+1;
}