-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathParseDateTransformation.cs
83 lines (70 loc) · 2.87 KB
/
ParseDateTransformation.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// -----------------------------------------------------------------------
// <copyright file="ParseDateTransformation.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace OpenScraping.Transformations
{
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
public class ParseDateTransformation : ITransformationFromObject, ITransformationFromHtml
{
public object Transform(Dictionary<string, object> settings, object input)
{
if (input != null && input is string)
{
var rawDate = (string)input;
return ParseDate(settings, rawDate);
}
return null;
}
public object Transform(Dictionary<string, object> settings, HtmlNodeNavigator nodeNavigator, List<HtmlAgilityPack.HtmlNode> logicalParents)
{
var rawDate = nodeNavigator?.Value ?? nodeNavigator?.CurrentNode?.InnerText;
if (rawDate != null)
{
return ParseDate(settings, rawDate);
}
return null;
}
private object ParseDate(Dictionary<string, object> settings, string rawDate)
{
string format = null;
var formatProvider = CultureInfo.InvariantCulture;
var dateStyle = DateTimeStyles.None;
if (settings != null)
{
if (settings.ContainsKey("_format") && ((JValue)settings["_format"]).Type == JTokenType.String)
{
format = settings["_format"].ToString();
}
if (settings.ContainsKey("_formatProvider") && ((JValue)settings["_formatProvider"]).Type == JTokenType.String)
{
var rawFormatProvider = settings["_formatProvider"].ToString();
formatProvider = new CultureInfo(rawFormatProvider);
}
if (settings.ContainsKey("_dateStyle") && ((JValue)settings["_dateStyle"]).Type == JTokenType.String)
{
var rawDateStyle = settings["_dateStyle"].ToString();
dateStyle = (DateTimeStyles)Enum.Parse(typeof(DateTimeStyles), rawDateStyle);
}
}
if (format != null)
{
format = settings["_format"].ToString();
if (DateTime.TryParseExact(rawDate, format, formatProvider, dateStyle, out DateTime date))
{
return date;
}
}
else if (DateTime.TryParse(rawDate, formatProvider, dateStyle, out DateTime date))
{
return date;
}
return null;
}
}
}