Joda time PeriodFormatterBuilder, can I omit weeks and use only days? - java

I have seen this, but is it possible to use only month and days, not weeks?
For example, instead of "1 month 2 weeks 2 days", I want "1 month 16 days".

You can use a solution similar to the answer you linked, but you'll also need to use a org.joda.time.PeriodType to normalized the period:
// 1 month, 2 weeks and 2 days
Period p = new Period(0, 1, 2, 2, 0, 0, 0, 0);
PeriodFormatter fmt = new PeriodFormatterBuilder()
// months
.appendMonths().appendSuffix(" month", " months").appendSeparator(" and ")
// days
.appendDays().appendSuffix(" day", " days")
.toFormatter();
System.out.println(fmt.print(p.normalizedStandard(PeriodType.yearMonthDayTime())));
This will print:
1 month and 16 days

Related

Java - How to format a mix of strings and integers using printf() to get equal length in the output?

I am having issues formatting this correctly:
starting mechanical cuchoo clock time [ 0:00:00], total drift = 0.00 seconds
after 1 day mechanical cuchoo clock time [23:59:00], total drift = 60.00 seconds
The correct formatting is:
starting mechanical cuckoo clock time [ 0:00:00], total drift = 0.00 seconds
after 1 day mechanical cuckoo clock time [23:59:00], total drift = 60.00 seconds
I tried this and it actually works but is there a better way?
System.out.printf("%60s", this.getClockType() + " cuchoo clock time [" + time.formattedReportedTime() +
"], " + "total drift = ");
System.out.printf("%s", fmt.format(time.getTotalDrift()) + "\n");
Here a small snippet in addition to the answer from Caio.
String format =
"%12s mechanical cuckoo clock time [%8s], total drift = %5.2f seconds%n";
System.out.printf(format, "starting", "0:00:00", 0.0);
System.out.printf(format, "after 1 day", "23:59:00", 60.0);
output
starting mechanical cuckoo clock time [ 0:00:00], total drift = 0.00 seconds
after 1 day mechanical cuckoo clock time [23:59:00], total drift = 60.00 seconds
%12s - the (first) parameter will be formatted as left padded string with 12 characters width
%8s - as above, the (second) parameter with 8 characters
%5.2f - the (third) parameter, which must be a floating point type, will be formated with a width of 5 charcaters and a precision of 2
You should check this link out. It's the Formatter Class doc it's super useful!

Java delete numbers behind comma

I want to calculate Days, Hours etc.
I want to make it like this:
184 Seconds / 60 = 3,0666666666667
Means 3 Minutes.
0,666666666667 * 60 = 4
So 184 Seconds are 3 Min. und 4 Seconds.
Now i dont know how to bring this into Java. I need a function to seperate the Pre-Comma Value from the After-Comma Value.
It's just a simple example. I want to do this with years,weeks,days and so on
It seems that you are looking for modulo (reminder) operator %. Also there is no "after comma value" in integers words so 184 / 60 = 3 not 3.06666.
int time = 184;
int minutes = time / 60;
int seconds = time % 60;
System.out.println(minutes + " minutes : " + seconds + " seconds");
Output: 3 minutes : 4 seconds
You can also use Period from JodaTime library.
int time = 184;
Period period = new Period(time * 1000);//in milliseconds
System.out.printf("%d minutes, %d seconds%n", period.getMinutes(),
period.getSeconds());
which will print 3 minutes, 4 seconds.
Just use %, /, and a little math:
int totalSeconds = 184;
int minutes = totalSeconds/60; //will be 3 minutes
int seconds = totalSeconds%60; // will be 4 seconds

How to display exact date difference in php [duplicate]

This question already has answers here:
Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
(32 answers)
Closed 8 years ago.
My Question is Little bit tricy .
i have to display date difference. (i find out date difference in terms of 2 year 7 month 3 days 5 hrs 30 min.)
Now how i display upto exact 2 higher values
please consider given case
case 1 : date difference is 0 year 2 month 21 days 7 hrs 30 min
output must be : 2 Month 21 days
case 2 : 0 year 0 month 0 days 7 hrs 20 min
output must be : 7 hours 21 days
If your date differences is in the exact form as in your question (separated with " ") and formatted as strings. This will do the trick.
<?php
function display_times($string){
$pieces = explode(" ",$string);
$num_disp = 0;
foreach($pieces as $i => $pice){
if(is_numeric($pice) && intval($pice) != 0){
echo $pice." ".$pieces[$i+1]." ";
$num_disp++;
if($num_disp >= 2) break;
}
}
}
$case1 = "0 year 2 month 21 days 7 hrs 30 min";
$case2 = "0 year 0 month 0 days 7 hrs 20 min";
display_times($case1);
echo PHP_EOL;
display_times($case2);
?>
You can modify this function. Replace 3rd parameter with $depth and modify array_slice line, like on demo.
Use examples :
echo time_diff_string('2013-05-01 00:22:35', 'now', 1), "\n";
echo time_diff_string('2013-05-01 00:22:35', 'now', 2), "\n";
echo time_diff_string('2013-05-01 00:22:35', 'now', 3), "\n";
echo time_diff_string('2013-05-01 00:22:35', 'now', 4), "\n";
Output :
6 months ago
6 months, 6 days ago
6 months, 6 days, 12 hours ago
6 months, 6 days, 12 hours, 6 minutes ago
Demo.

Subtraction of 1ms leads to unexpected behaviour

What is wrong? I assume that if I subtract 1ms from 1 Jan 1980 0:0:0 then I've got 1979. But I must subtract about 500+ ms for this. Please, give me a hint.
val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
cal.set(1980, 0, 1, 0, 0, 0)
val date = new Date
date.setTime(cal.getTimeInMillis()) // <- 1980 Jan 01 0:0:0
date.setTime(cal.getTimeInMillis() - 1) // <- 1980 Jan 01 0:0:0 too !!!
Updated.
The solution is
val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
cal.setTimeInMillis(0)
cal.set(1980, 0, 1, 0, 0, 0)
With Calendar.set(year, month, day, hourOfDay, minute, second) no milliseconds are set. Consequently the Calendar implementation sets the milliseconds to "unknown" which is actually treated as the midpoint within the given second.
Subtracting 500ms means you just step over the midpoint. Same should happen if you add 500ms, which should bring you just over the second. Actually subtracting 500ms works and you must add 620ms to see the next second.

Parsing a String to a Date [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I have a String 2012-10-23 which I need to convert into a Date object.
Can I pass this string directly to the below function
Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);
Date date = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(string);
for 2012-10-23 your format should be "yyyy-MM-dd"
String string = "2012-10-23";
Date date = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(string);
Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
No you can't, this is how
String string = "2012-10-23";
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(string);

Categories