November 13, 2007

DateTime

Here are some links regarding DateTime string formatting and parsing: Truncating Milliseconds
private static DateTime TruncateMilliSeconds(DateTime dt)
{
  DateTime trunc = new DateTime(dt.Ticks - (10000*dt.Millisecond));
  Debug.Assert(trunc.Millisecond == 0);
  return trunc;
}
Parsing a date from a non standard form
DateTime.TryParseExact(dateStart, "yyyyMMdd",
  System.Globalization.CultureInfo.CurrentCulture,
  System.Globalization.DateTimeStyles.AssumeLocal, out m_StartDate);
Here is another example that will parse this string "Sun, 30 Jun 2013 14:14:01 +0100"
DateTime when = DateTime.MinValue;
string form = @"ddd, dd MMM yyyy HH':'mm':'ss K";
DateTime.TryParseExact(this.rawDateTime, form, 
  System.Globalization.CultureInfo.CurrentCulture,
  System.Globalization.DateTimeStyles.AssumeLocal, 
  out when);
Converting a date to a non standard string form
string datTimeStr = DateTime.UtcNow.ToString("yyyyMMdd"); 
where
M=month digit, y=year digit, d=day digit
h=hour digit, m=minute digit, s=second digit

Here is an example of this from renaming photos extracted from a digital camera
public class PhotoBackupOptions
{
    private string m_fileDateFormatStr = "yyyy_MMdd_HHmm";
    private string m_filenamePrefix = "Photo_";

    public string FileNameDateFormatStr
    {
        get { return m_fileDateFormatStr; }
    }

    public string FileNamePrefix
    {
        get { return m_filenamePrefix; }
    }

    public string GetPhotoFileName(FileInfo fsi)
    {
        Debug.Assert((fsi != null) && fsi.Exists);
        string res = fsi.Name;
        if (FileNameDateFormatStr.Length > 0)
        {
            DateTime dt = fsi.CreationTime;
            res = FileNamePrefix + 
                  dt.ToString(FileNameDateFormatStr) +
                  fsi.Extension;
        }
        return res;
    }
}
Here is a static method to load a date from a photo using WPF
// Retrieve the datetime from an image WITHOUT loading the whole thing
public static bool GetDateTakenFromImage(FileInfo fi, out DateTime dateTaken)
{
    dateTaken = DateTime.MinValue;
    bool found = false;
    try
    {
        using (FileStream fs = new FileStream(fi.FullName, 
            FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            BitmapMetadata md = (BitmapMetadata)BitmapFrame.Create(fs).Metadata;              
            found = DateTime.TryParse(md.DateTaken, out dateTaken);
        }
    }
    catch (Exception)
    {
        Trace.WriteLine("Could not get DateTaken from the image: \'" + fi.FullName + "\'");
    }
    return found;
}

No comments: