Handle DateTime parsing for UTC strings
This commit is contained in:
parent
c6b998d00b
commit
1febb9a211
|
|
@ -1,5 +1,6 @@
|
|||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Elsa.Services.Models;
|
||||
|
|
@ -14,17 +15,7 @@ namespace Elsa.Expressions
|
|||
string expression,
|
||||
Type returnType,
|
||||
ActivityExecutionContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (returnType == typeof(string) || returnType == typeof(object))
|
||||
return Task.FromResult<object?>(expression);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(expression))
|
||||
return Task.FromResult((object?) null);
|
||||
|
||||
var converter = TypeDescriptor.GetConverter(returnType);
|
||||
var value = converter.CanConvertFrom(typeof(string)) ? converter.ConvertFrom(expression) : default;
|
||||
return Task.FromResult(value)!;
|
||||
}
|
||||
CancellationToken cancellationToken) =>
|
||||
Task.FromResult(expression.Parse(returnType));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +1,27 @@
|
|||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Elsa
|
||||
{
|
||||
public static class StringExtensions
|
||||
{
|
||||
public static T Parse<T>(this string value) => (T)value.Parse(typeof(T));
|
||||
public static T? Parse<T>(this string value) => (T?)value.Parse(typeof(T));
|
||||
|
||||
public static object Parse(this string value, Type targetType)
|
||||
public static object? Parse(this string value, Type targetType)
|
||||
{
|
||||
if (typeof(string) == targetType || typeof(object) == targetType || targetType == default)
|
||||
if (typeof(string) == targetType || typeof(object) == targetType || targetType == default!)
|
||||
return value;
|
||||
|
||||
// Handling DateTime explicitly due to an issue with converting UTC strings to DateTime as outlined here: https://stackoverflow.com/questions/11130912/datetimeconverter-converting-from-utc-string
|
||||
if(targetType == typeof(DateTime))
|
||||
return DateTime.Parse(value, null, DateTimeStyles.RoundtripKind);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
return null!;
|
||||
|
||||
var converter = TypeDescriptor.GetConverter(targetType);
|
||||
return converter.ConvertFromString(value)!;
|
||||
return converter.CanConvertFrom(typeof(string)) ? converter.ConvertFrom(value) : default;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -57,7 +57,8 @@ namespace Elsa.Expressions
|
|||
[StubActivityExecutionContext] ActivityExecutionContext context)
|
||||
{
|
||||
var result = await sut.EvaluateAsync("2001-03-04T12:45:32Z", typeof(DateTime), context, default);
|
||||
Assert.Equal(new DateTime(2001, 03, 04, 12, 45, 32, DateTimeKind.Utc), result);
|
||||
var expected = new DateTime(2001, 03, 04, 12, 45, 32, DateTimeKind.Utc);
|
||||
Assert.Equal(expected, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue