How to convert date to Julian date in Dart

152 Views Asked by At

I need convert Julian Data gets from my API to Gregorian date like this:

Input 2023150
Output 2023-May-30

How can this be done?

1

There are 1 best solutions below

3
lrn On

For actual Julian Day conversion, you can use:

// Noon of 1st of January, 4713 BC in the Julian calendar,
// or the 24th of November, 4713 BC in the proleptic Gregorian calendar.
final _julianEpoch = DateTime.utc(-4713, 11, 24, 12);

/// Convert UTC [DateTime] to, possibly fractional, Julian day.
double toJulian(DateTime gregorianDay) {
  if (!gregorianDay.isUtc) {
    throw ArgumentError.value(gregorianDay, "gregorianDay", "Must be UTC date");
  }
  return gregorianDay.difference(_julianEpoch).inMilliseconds /
      Duration.millisecondsPerDay;
}

/// Convertes, possibly fractional, Julian day value to UTC [DateTime].
DateTime fromJulian(num julianDay) {
  return _julianEpoch.add(Duration(
      milliseconds: (julianDay * Duration.millisecondsPerDay).floor()));
}

It seems that what you have is just year * 1000 + day-in-year. Converting that to a day should be easier:

DateTime fromDayInYear(int yearAndDayInYear) =>
  DateTime.utc(yearAndDayInYear ~/ 1000, 1, yearAndDayInYear.remainder(1000));