Files
jdescopingtool/NEW/src/JdeScoping.DataSync/Services/ParameterFormatConverter.cs
T

80 lines
2.8 KiB
C#

namespace JdeScoping.DataSync.Services;
/// <summary>
/// Converts parameter values to JDE-specific formats with timezone support.
/// </summary>
public class ParameterFormatConverter
{
private readonly TimeZoneInfo _timezone;
/// <summary>
/// Initializes a new instance of the <see cref="ParameterFormatConverter"/> class.
/// </summary>
/// <param name="timezone">
/// The timezone to use for conversions.
/// Accepts "UTC", "LOCAL", or a valid timezone ID (e.g., "Eastern Standard Time").
/// </param>
public ParameterFormatConverter(string timezone)
{
_timezone = timezone.ToUpperInvariant() switch
{
"UTC" => TimeZoneInfo.Utc,
"LOCAL" => TimeZoneInfo.Local,
_ => TimeZoneInfo.FindSystemTimeZoneById(timezone)
};
}
/// <summary>
/// Converts a DateTime value to the specified format.
/// </summary>
/// <param name="value">The DateTime value to convert.</param>
/// <param name="format">
/// The format to convert to. Supported formats:
/// - "jdejulian": JDE Julian date (CYYDDD format)
/// - "jdetime": JDE time (HHMMSS as integer)
/// - null: Returns the timezone-adjusted DateTime
/// </param>
/// <returns>The converted value.</returns>
/// <exception cref="ArgumentException">Thrown when an unknown format is specified.</exception>
public object Convert(DateTime value, string? format)
{
var adjusted = TimeZoneInfo.ConvertTime(value, _timezone);
return format?.ToLowerInvariant() switch
{
"jdejulian" => ToJdeJulianDate(adjusted),
"jdetime" => ToJdeTime(adjusted),
null => adjusted,
_ => throw new ArgumentException($"Unknown format: {format}")
};
}
/// <summary>
/// Converts a DateTime to JDE Julian date format (CYYDDD).
/// </summary>
/// <param name="date">The date to convert.</param>
/// <returns>
/// The JDE Julian date as an integer where:
/// - C is the century bit (0 for 1900s, 1 for 2000s)
/// - YY is the two-digit year
/// - DDD is the day of year (001-366)
/// </returns>
public static int ToJdeJulianDate(DateTime date)
{
int century = date.Year >= 2000 ? 1 : 0;
int year = date.Year % 100;
int dayOfYear = date.DayOfYear;
return century * 100000 + year * 1000 + dayOfYear;
}
/// <summary>
/// Converts a DateTime to JDE time format (HHMMSS).
/// </summary>
/// <param name="time">The time to convert.</param>
/// <returns>The JDE time as an integer in HHMMSS format.</returns>
public static int ToJdeTime(DateTime time)
{
return time.Hour * 10000 + time.Minute * 100 + time.Second;
}
}