using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
namespace Darkthread
{
class Program
{
//getTime() in Javascript is milliseconds since January 1, 1970
//Ticks in .NET is nanoseconds since January 1, 0000
//new DateTime(1970, 1, 1).Ticks = 621355968000000000
static long baseTicks = 621355968000000000;
//Convert Javascript ticks to DateTime
static string GetDateTimeString(long jsTicks, int utcDiff = 0)
{
return new DateTime(jsTicks * 10000 + baseTicks).AddHours(utcDiff)
.ToString("yyyy/MM/ddTHH:mm:ssZ");
}
//Convert JSON date string to DateTime
static string GetDateTimeString(string jsonDateString)
{
int p = jsonDateString.IndexOf("(") + 1;
string numStr = jsonDateString.Substring(p,
jsonDateString.IndexOf(")") - p
);
int utcDiff = 0;
string[] a = numStr.Split('+', '-');
if (a.Length == 2)
{
utcDiff = (numStr.Contains("-") ? -1 : 1) *
int.Parse(a[1].Substring(0, 2));
numStr = a[0];
}
return GetDateTimeString(long.Parse(numStr), utcDiff);
}
static void Main(string[] args)
{
if (args.Length < 1 || args.Length > 2)
{
Console.WriteLine("Syntax: ConvJsonDate file_name or " +
"ConvJsonDate file_name_*.ext output_path");
return;
}
string fn = args[0];
string[] files = new string[] { fn };
//for wildcard search
if (fn.Contains("*"))
{
string srcFolder = Path.GetDirectoryName(fn);
//if no path assigned, use current folder
if (string.IsNullOrEmpty(srcFolder))
srcFolder = ".";
string pattern = Path.GetFileName(fn);
files = Directory.GetFiles(srcFolder, pattern);
}
//get output path if assigned
string path = args.Length > 1 ? args[1] : null;
//define regular expression pattern
Regex re = new Regex(@"\\/Date\([0-9+-]+\)\\/");
StringBuilder sb = new StringBuilder();
foreach (string f in files)
{
using (StreamReader sr = new StreamReader(f))
{
string line;
sb.Length = 0;
while ((line = sr.ReadLine()) != null)
//convert \/Date(....)\/ to yyyy-MM-ddTHH:mm:ssZ
sb.AppendLine(
re.Replace(line, (o) => GetDateTimeString(o.Value)));
if (string.IsNullOrEmpty(path))
//if no path assigned, output the converted text to console
Console.Write(sb.ToString());
else
//if path is assigned, dump the converted text to files
try
{
File.WriteAllText(Path.Combine(path, Path.GetFileName(f)),
sb.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
}
}
}
}
}