//-----------------------------------------------------------------------
//
// Copyright (c) Outercurve Foundation. All rights reserved.
//
//-----------------------------------------------------------------------
namespace DotNetOpenAuth.Messaging {
using System;
using System.Globalization;
using DotNetOpenAuth.Messaging.Reflection;
///
/// Translates between a and the number of seconds between it and 1/1/1970 12 AM
///
internal class TimestampEncoder : IMessagePartEncoder {
///
/// The reference date and time for calculating time stamps.
///
internal static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
///
/// Initializes a new instance of the class.
///
public TimestampEncoder() {
}
///
/// Encodes the specified value.
///
/// The value. Guaranteed to never be null.
///
/// The in string form, ready for message transport.
///
public string Encode(object value) {
if (value == null) {
return null;
}
var timestamp = (DateTime)value;
TimeSpan secondsSinceEpoch = timestamp - Epoch;
return ((int)secondsSinceEpoch.TotalSeconds).ToString(CultureInfo.InvariantCulture);
}
///
/// Decodes the specified value.
///
/// The string value carried by the transport. Guaranteed to never be null, although it may be empty.
///
/// The deserialized form of the given string.
///
/// Thrown when the string value given cannot be decoded into the required object type.
public object Decode(string value) {
if (value == null) {
return null;
}
var secondsSinceEpoch = int.Parse(value, CultureInfo.InvariantCulture);
return Epoch.AddSeconds(secondsSinceEpoch);
}
}
}