This question already has answers here:
Do we have a TimeSpan sort of class in Java
(4 answers)
Closed 6 years ago.
I am trying to convert the following code which is in c# to java. And I am facing difficulty in converting it. Please can anyone suggest me a simple way to do it in Java.
DateTime StartDate = new DateTime(PWUpdatedOn.Year, 01, 01);
TimeSpan ts = new TimeSpan(PWUpdatedOn.Ticks - StartDate.Ticks);
//Response.Write(ts.Days+1);
days = ts.Days + 1;
lngN = 0;
PWUpdatedOn.Year = 2016 // current year
As Jigar Joshi answered in an other Question.
Interval from JodaTime will do..
A time interval represents a period of time between two instants. Intervals >are inclusive of the start instant and exclusive of the end. The end instant is always greater than or equal to the start instant.
Intervals have a fixed millisecond duration. This is the difference between the start and end instants.
The duration is represented separately by ReadableDuration. As a result, intervals are not comparable. To compare the length of two intervals, you should compare their durations.
An interval can also be converted to a ReadablePeriod. This represents the difference between the start and end points in terms of fields such as years and days.
Interval is thread-safe and immutable.
I am not sure what Ticks are in C#. But it would be something like:
LocalDateTime startDate = LocalDateTime.of(PWUpdatedOn.getYear(), 1, 1);
Period ts = Period.between(PWUpdatedOn, startDate.toLocalDate());
days = ts.getDays() + 1;
Note that Period.between() requires two LocalDate instances. If PWUpdateOn is a LocalDateTime instance, it needs to be converted with the method toLocalDate().
Some potentially relevant remarks: for zoned datetimes, use ZonedDateTime rather than LocalDateTimel; all time and period objects are immutable in Java.
Related
This question already has answers here:
LocalDate to java.util.Date and vice versa simplest conversion? [duplicate]
(7 answers)
How do I get a Date without time in Java?
(23 answers)
Closed 3 years ago.
I want to get a Date without time, but always failed.
below is my codes:
long curLong = System.currentTimeMillis();
curLong = curLong - curLong % TimeUnit.DAYS.toMillis(1);
Date date = new Date(curLong);
System.out.println("date = " + date);
the output:
date = Mon Oct 28 08:00:00 CST 2019
anyone knows why? Thank you
It is not recommended to use java.util.Date anymore. It was called Date but doesn't necessarily hold only the date information but information about the time additionally.
Use this:
LocalDate today = LocalDate.now();
and print it as
System.out.println(today.format(DateTimeFormatter.ISO_DATE);
using the ISO date format. You can define your own formatting pattern using a
DateTimeFormatter.ofPattern("dd.MM.yyyy");
for example.
You can use java.time.LocalDate.now() to get just the date.
Anyway, your case doesn't work as you expect because you are doing nothing to remove the time from the date: you are just "repressing" it, that's why it's zero. If you want to continue this way you could always substring it (substring the Date.toString() of course I meant).
Hope I helped.
java.util.Date's javadoc states:
The class Date represents a specific instant in time, with millisecond precision.
Thats why you have date with time
If you want a date you can use : java.time.LocalDate.now() (Java 8+)
First of all, stop using the old java.util.Date. The new Java 8 date and time API has much better classes for all date and time operations.
The LocalDate class does exactly what you want.
The current date can be obtained by LocalDate.now().
It also has a lot of facilities to add and subtract days, months etc. and it takes into consideration all the calendar special cases for you.
This question already has answers here:
How to calculate the number of days in a period?
(3 answers)
Closed 3 years ago.
I have Period object which comes from api. I have to calculate total days it contains. I found many answers how to get days between two dates, but no one answers how I can get total days exactly from Period object.
E.g:
LocalDate start = LocalDate.now();
LocalDate end = LocalDate.now().plusYears(1);
Period period = Period.between(start, end);
I have only the last object with name period and i have to get 365 days from it.
getDays() returns only days count within one month. And I don't have two dates objects. Only period.
You might wanna read up on the Period Java API Documentation.
Period represents the time duration in this format, "2 years, 3 months and 4 days"
For your case above, its exactly 1 year, 0 Months and 0 days.
When you do a get Days, it will show you 0 days.
Try with an end date of LocalDate end = LocalDate.now().minusDays(398);
The getYears(), getMonths(), getDays() each returns its own value. ;)
Since you already have a Period object, you can do a function to get the number of days from a Period Object using the getYears, getMonths and getDays() methods then sum them together.
The Duration object might help with that.
did you tried import java.time package and use Period class? if you didn't, here's a little help for it https://docs.oracle.com/javase/8/docs/api/java/time/Period.html
This question already has answers here:
Any new method to get current time with accuracy in microseconds in Java now?
(3 answers)
Closed 6 years ago.
In java Calendar class while adding milliseconds I am missing the decimal precession. Since method expects integer
For example:
1000/12 = 83.333333
In java
Calendar c = Calendar.getInstance();
c.add(Calendar.MILLISECOND, (integer));
Which takes only 83 and .33333 is missed.
Does anybody know how to handle this scenario in java ?
java.util.Calendar keeps time information at the level of milliseconds,
An instant in time can be represented by a millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian).
java.time.LocalDateTime has a sensitivity in the level of nanosecond.
Time is represented to nanosecond precision. For example, the value
"2nd October 2007 at 13:45.30.123456789" can be stored in a
LocalDateTime.
so if you need microsecond or nanosecond level information, you can not use java.util.Calendar, and you should use java.time.LocalDateTime.
I have a date in the far past.
I found out what the duration is between this date and now.
Now I would like to know - how much is this in years?
I came up withthis solution using Java8 API.
This is a monstrous solution, since I have to convert the duration to Days manually first, because there will be an UnsupportedTemporalTypeException otherwise - LocalDate.plus(SECONDS) is not supported for whatever reason.
Even if the compiler allows this call.
Is there a less verbous possibility to convert Duration to years?
LocalDate dateOne = LocalDate.of(1415, Month.JULY, 6);
Duration durationSinceGuss1 = Duration.between(LocalDateTime.of(dateOne, LocalTime.MIDNIGHT),LocalDateTime.now());
long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDate.now(),
LocalDate.now().plus(
TimeUnit.SECONDS.toDays(
durationSinceGuss1.getSeconds()),
ChronoUnit.DAYS) );
/*
* ERROR -
* LocalDate.now().plus(durationSinceGuss1) causes an Exception.
* Seconds are not Supported for LocalDate.plus()!!!
* WHY OR WHY CAN'T JAVA DO WHAT COMPILER ALLOWS ME TO DO?
*/
//long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDate.now(), LocalDate.now().plus(durationSinceGuss) );
/*
* ERROR -
* Still an exception!
* Even on explicitly converting duration to seconds.
* Everything like above. Seconds are just not allowed. Have to convert them manually first e.g. to Days?!
* WHY OR WHY CAN'T YOU CONVERT SECONDS TO DAYS OR SOMETHING AUTOMATICALLY, JAVA?
*/
//long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDate.now(), LocalDate.now().plus(durationSinceGuss.getSeconds(), ChronoUnit.SECONDS) );
Have you tried using LocalDateTime or DateTime instead of LocalDate? By design, the latter does not support hours/minutes/seconds/etc, hence the UnsupportedTemporalTypeException when you try to add seconds to it.
For example, this works:
LocalDateTime dateOne = LocalDateTime.of(1415, Month.JULY, 6, 0, 0);
Duration durationSinceGuss1 = Duration.between(dateOne, LocalDateTime.now());
long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDateTime.now(), LocalDateTime.now().plus(durationSinceGuss1) );
System.out.println(yearsSinceGuss); // prints 600
Although the accepted answer of #Matt Ball tries to be clever in usage of the Java-8-API, I would throw in following objection:
Your requirement is not exact because there is no way to exactly convert seconds to years.
Reasons are:
Most important: Months have different lengths in days (from 28 to 31).
Years have sometimes leap days (29th of February) which have impact on calculating year deltas, too.
Gregorian cut-over: You start with a year in 1415 which is far before first gregorian calendar reform which cancelled full ten days, in England even 11 days and in Russia more. And years in old Julian calendar have different leap year rules.
Historic dates are not defined down to second precision. Can you for example describe the instant/moment of the battle of Hastings? We don't even know the exact hour, just the day. Assuming midnight at start of day is already a rough and probably wrong assumption.
Timezone effects which have impact on the length of day (23h, 24h, 25h or even different other lengths).
Leap seconds (exotic)
And maybe the most important objection to your code:
I cannot imagine that the supplier of the date with year 1415 has got the intention to interprete such a date as gregorian date.
I understand the wish for conversion from seconds to years but it can only be an approximation whatever you choose as solution. So if you have years like 1415 I would just suggest following very simple approximation:
Duration d = ...;
int approximateYears = (int) (d.toDays() / 365.2425);
For me, it is sufficient in historic context as long as we really want to use a second-based duration for such an use-case. It seems you cannot change the input you get from external sources (otherwise it would be a good idea to contact the duration supplier and ask if the count of days can be supplied instead). Anyway, you have to ask yourself what kind of year definition you want to apply.
Side notes:
Your complaint "WHY OR WHY CAN'T JAVA DO WHAT COMPILER ALLOWS ME TO DO?" does not match the character of new java.time-API.
You expect the API to be type-safe, but java.time (JSR-310) is not designed as type-safe and heavily relies on runtime-exceptions. The compiler will not help you with this API. Instead you have to consult the documentation in case of doubt if any given time unit is applicable on any given temporal type. You can find such an answer in the documentation of any concrete implementation of Temporal.isSupported(TemporalUnit). Anyway, the wish for compile-safety is understandable (and I have myself done my best to implement my own time library Time4J as type-safe) but the design of JSR-310 is already set in stone.
There is also a subtile pitfall if you apply a java.time.Duration on either LocalDateTime or Instant because the results are not exactly comparable (seconds of first type are defined on local timeline while seconds of Instant are defined on global timeline). So even if there is no runtime exception like in the accepted answer of #Matt Ball, we have to carefully consider if the result of such a calculation is reasonable and trustworthy.
Use Period to get the number of years between two LocalDate objects:
LocalDate before = LocalDate.of(1415, Month.JULY, 6);
LocalDate now = LocalDate.now();
Period period = Period.between(before, now);
int yearsPassed = period.getYears();
System.out.println(yearsPassed);
This question already has answers here:
How can I convert the result of System.nanoTime to a date in Java?
(3 answers)
Closed 7 years ago.
I am writing a code for implementing Stop Watch. I capture a moment with System.nanoTime(). But I would also like to convert and store that moment into a date field. When I try to use new Date(long msec), it's giving me some absurd date-time value. Can anyone help me how to get this done?
System.nanoTime is not the current time:
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.
This is why you're experiencing "some absurd date-time value".
Use System.currentTimeMillis if you want the date(s) you've captured as milliseconds (see: unix time):
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.