Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Create ConvertStandardDateFormatToJulianDateAndVice-versa.swift (#5516)
Browse files Browse the repository at this point in the history
Description:
- Added two new functions in the utility module:
  1. `convertToJulianDate(dateString: String) -> String?`: Converts a standard date (yyyy-MM-dd format) to a Julian date format. Utilizes DateFormatter for parsing and Calendar for day-of-year calculation.
  2. `convertFromJulianDate(julianDateString: String) -> String?`: Converts a Julian date format to a standard date (yyyy-MM-dd format). Extracts the year and day of the year from the Julian date, then constructs the standard date using Calendar.

- Included error handling to manage invalid date formats and out-of-range values.

- Added unit tests for both functions to validate the correctness of the conversions under various scenarios including leap years.

Co-authored-by: Anandha Krishnan S <[email protected]>
  • Loading branch information
bulutg and anandfresh authored Mar 8, 2024
1 parent 9624b3f commit 515e191
Showing 1 changed file with 49 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import Foundation

func convertToJulianDate(dateString: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")

if let date = dateFormatter.date(from: dateString) {
let year = Calendar.current.component(.year, from: date)
let dayOfYear = Calendar.current.ordinality(of: .day, in: .year, for: date)!

return String(format: "%04d%03d", year, dayOfYear)
}

return nil
}

func convertFromJulianDate(julianDateString: String) -> String? {
guard julianDateString.count == 7,
let year = Int(julianDateString.prefix(4)),
let dayOfYear = Int(julianDateString.suffix(3)) else {
return nil
}

var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.day = dayOfYear

if let date = Calendar.current.date(from: dateComponents) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")

return dateFormatter.string(from: date)
}

return nil
}

// Example Usage
let standardDate = "2023-06-10"
if let julianDate = convertToJulianDate(dateString: standardDate) {
print("Julian Date: \(julianDate)")
}

let julianDate = "2023160"
if let standardDate = convertFromJulianDate(julianDateString: julianDate) {
print("Standard Date: \(standardDate)")
}

1 comment on commit 515e191

@vercel
Copy link

@vercel vercel bot commented on 515e191 Mar 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.