Como converter uma data retornada por um Json para TDateTime?
Normalmente ao receber um json, a data vem em um padrão um pouco
diferente, conforme o exemplo abaixo:
1
2
3
4
5
6
7
8
| {
"cdPlayer": 3,
"nmPlayer": "Player Name",
"dtCreate": "2016-08-24T22:53:31.687",
"dtDay": "2017-05-01",
"dtChange": null,
"idStatus": true
} |
{
"cdPlayer": 3,
"nmPlayer": "Player Name",
"dtCreate": "2016-08-24T22:53:31.687",
"dtDay": "2017-05-01",
"dtChange": null,
"idStatus": true
}
Se tentar Usar o StrToDate, irá dar erro!
Felizmente a uma função para resolver isto!
Vamos a ela:
Antes, declare DateUtils ou System.DateUtils;
1
2
3
4
5
6
7
8
9
10
11
12
13
| function JSONDate_To_Datetime(JSONDate: string): TDatetime;
var Year, Month, Day, Hour, Minute, Second, Millisecond: Word;
begin
Year := StrToInt(Copy(JSONDate, 1, 4));
Month := StrToInt(Copy(JSONDate, 6, 2));
Day := StrToInt(Copy(JSONDate, 9, 2));
Hour := StrToInt(Copy(JSONDate, 12, 2));
Minute := StrToInt(Copy(JSONDate, 15, 2));
Second := StrToInt(Copy(JSONDate, 18, 2));
Millisecond := Round(StrToFloat(Copy(JSONDate, 19, 4)));
Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, Millisecond);
end; |
function JSONDate_To_Datetime(JSONDate: string): TDatetime;
var Year, Month, Day, Hour, Minute, Second, Millisecond: Word;
begin
Year := StrToInt(Copy(JSONDate, 1, 4));
Month := StrToInt(Copy(JSONDate, 6, 2));
Day := StrToInt(Copy(JSONDate, 9, 2));
Hour := StrToInt(Copy(JSONDate, 12, 2));
Minute := StrToInt(Copy(JSONDate, 15, 2));
Second := StrToInt(Copy(JSONDate, 18, 2));
Millisecond := Round(StrToFloat(Copy(JSONDate, 19, 4)));
Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, Millisecond);
end;
Fonte: https://stackoverflow.com/questions/39427597/how-to-parse-to-tdatetime-a-date-time-returned-from-a-json-string-in-delphi-xe-1
Dúvidas ou sugestões? Deixe o seu comentário!
-
Giovani Da Cruz
-
7.682 views
- 0 comentários
- 27 de maio de 2017
Está gostando do conteúdo? Considere pagar um cafezinho para nossa equipe!
Posts Relacionados - Continue Aprendendo