Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Timespan equivalent in java? [duplicate]

Tags:

java

timespan

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

2 Answers

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.

like image 100
Bytehawks Avatar answered Sep 09 '25 01:09

Bytehawks


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.

like image 22
Albert Waninge Avatar answered Sep 09 '25 00:09

Albert Waninge