I am trying to store Date in Indian format in MongoDB, However it is storing date in UTC format, Is there anyway to store Date as Indian format in MongoDB from DotNet API? Or anyother global workaround there?
CodePudding user response:
I guess there is no way to store Date as Indian format in Mongo Db not only Indian format Date, Date Time can be only store as UTC Time in Mongo DB.
I don't want to store date as a different field, so I come up with an work around for that, The thing is we can store Date as in UTC format itself in DB but once we querying we can change that to IST format in API before performing any of our customized operation.
So I tried two set of different methods for convert to IST and Convert to UTC, And I did Benchmark on those methods also, And Adding/subtracting time method seems to be faster and using almost no memory allocated, Here is the code and Benchmark result
public static DateTime ConvertIstToUtc(DateTime date)
{
return TimeZoneInfo.ConvertTimeToUtc(date, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));
}
public static DateTime ConvertUtcToIst(DateTime date)
{
return TimeZoneInfo.ConvertTimeFromUtc(date,TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));
}
public static DateTime ConvertIstToUtcByAddSub(DateTime date)
{
return date.AddHours(-5).AddMinutes(-30);
}
public static DateTime ConvertUtcToIstByAddSub(DateTime date)
{
return date.AddHours(5).AddMinutes(30);
}
Method | Mean | Error | StdDev | Gen0 | Allocated |
---|---|---|---|---|---|
ConvertToIstMethod1 | 181.97 ns | 3.696 ns | 6.176 ns | 0.0381 | 80 B |
ConvertToUtcMethod1 | NA | NA | NA | - | - |
ConvertToIstAddSubMethod2 | 39.21 ns | 0.540 ns | 0.479 ns | - | - |
ConvertToUtcAddSubMethod2 | 52.96 ns | 1.097 ns | 1.708 ns | - | - |