4

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
Chirag Parmar
  • 833
  • 11
  • 26
  • 1
    Depends on which Java version you're looking to make it work. In Java 8 there are the `java.time.*` classes that can do that for you, but before that you'll either have to use the JodaTime library or do the math on your own using primitive values. – coladict Nov 21 '16 at 09:11
  • 1
    Check this https://docs.oracle.com/javase/tutorial/datetime/iso/period.html for java 8 – Shady Atef Nov 21 '16 at 09:11

2 Answers2

2

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.

Community
  • 1
  • 1
Bytehawks
  • 271
  • 4
  • 11
1

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.

Albert Waninge
  • 319
  • 1
  • 10