我有个自负的客户。令人惊讶的是,API期望所有的日期参数都在UTC+02:00中,并且不能只处理所提供的时区信息。现在,无论我做什么,我都不能使时区有点正确(+02:00)。以下代码始终打印+01:00,而不考虑我提供的时区。
TimeZoneInfo.ConvertTime(new DateTime(2020, 1, 8, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.FindSystemTimeZoneById("Asia/Magadan")).ToString("zzz")正如我前面提到的,这是一个生成的客户机,我无法控制它。所以我不能把json串行化程序弄乱。API:
List<GLJournalEntry> Create (PostGLJournalEntriesDTO body, string idempotencyKey = null);DTO:
public PostGLJournalEntriesDTO(List<GLAccountAmount> credits = default(List<GLAccountAmount>), List<GLAccountAmount> debits = default(List<GLAccountAmount>), string branchId = default(string), DateTime? date = default(DateTime?), string notes = default(string), string transactionId = default(string))
{
this.Credits = credits;
this.Debits = debits;
this.BranchId = branchId;
this.Date = date;
this.Notes = notes;
this.TransactionId = transactionId;
}JSON-模型:
"PostGLJournalEntriesDTO":{
"type":"object",
"properties":{
"date":{
"type":"string",
"format":"date-time",
"example":"2016-09-06T13:37:50+03:00",
"description":"Date/time stamp when the entries were recorded (Booking Date)"
},
"branchId":{
"type":"string",
"description":"The id of the assigned branch for the journal entries"
},
"notes":{
"type":"string",
"description":"Optional notes entered by the user when they performed the journal entry log"
},
"credits":{ "type":"array",
"description":"The list of GL Accounts to be credited with the corresponding amounts",
"items":{
"$ref":"#/definitions/GLAccountAmount"
}
},
"debits":{ "type":"array",
"description":"The list of GL Accounts to be debited with the corresponding amounts",
"items":{
"$ref":"#/definitions/GLAccountAmount"
}
},
"transactionId":{
"type":"string",
"description":"An id for the transaction. Not unique. Will be auto generated if not provided."
}
},
"description":"The representation of a payload for creating GL Journal Entries"
}交易的id。不是独一无二的。如果不提供,将自动生成。}
当我调用API时,会得到一个异常:
{“错误”:{“errorCode”:4,“errorSource”:“值2020-01-08T23:00:00+01:00的日期偏移量为+02:00",”errorReason“:”INVALID_PARAMETERS“}
如果我使用2020-01-08T23:00:00+02:00卷曲api,那么一切都正常。
很明显,这是它们端的一个bug (就像示例中所描述的+03:00的日期一样)。然而,我已经等不及他们帮我解决这个问题了,我需要找到一个解决办法(至少是一个中间的)。生成的客户机使用RestSharp来序列化json (Newtonsoft.Json.JsonConvert)。
发布于 2020-07-21 12:47:35
尽可能避免使用DateTime,而使用DateTimeOffset:
var sourceOffset = TimeSpan.Zero; // UTC
var source = new DateTimeOffset(2020, 1, 8, 0, 0, 0, sourceOffset);代码的其余部分不会改变:
var timezone = TimeZoneInfo.FindSystemTimeZoneById("Asia/Magadan");
var timezoneStr = TimeZoneInfo.ConvertTime(source, timezone).ToString("zzz");这将给出+11:00 (这对于马加丹时间是正确的)。如果需要将Magadan时间转换为UTC+2,则需要相应地更改偏移量和目标时区。
举个例子,下面是如何像当前由UTC+2时区观察到的那样进入Africa/Cairo:
var utcPlus2 = TimeZoneInfo.FindSystemTimeZoneById("Africa/Cairo");
var converted = TimeZoneInfo.ConvertTime(target, utcPlus2);
var dateTime = converted.DateTime;现在,dateTime值将是1/8/2020 2:00:00 AM --这是正确的,因为1/8/2020 0:00:00 AM UTC是1/8/2020 2:00:00 AM UTC+2。注意,虽然您无法从DateTime实例中获得正确的时区,但时间值本身是正确的。
https://stackoverflow.com/questions/63014592
复制相似问题