Une structure qui gère le unix timestamp

Contenu du snippet

J'ai précisément choisi le type valeur (structure) pour donner la possibilité de faire des calcul dessus. Les surcharges logiques ont été ajoutée tel que le +, -.

Merci de me faire part de vos suggestions pour améliorer le codage.

Source / Exemple :


/// <summary>
	/// <author>Simon Kari (Bismark Prods)</author>
	/// <date>17/09/2004</date>
	/// Structure de gestion du timestamp unix
	/// </summary>
	[Serializable()]
    public struct UnixTimestamp
	{
		private double _value;
		private double Value
		{
			get
			{
				return this._value;
			}
		}

		public UnixTimestamp(double initialValue)
		{
			if(initialValue < 0)throw new ArgumentException("Negative number not allowed","initialValue");
			this._value = initialValue;
		}

		public UnixTimestamp(DateTime initialValue)
		{
			if(initialValue.Year < 1970)throw new ArgumentException("Dates under 1970 not allowed","initialValue");
			DateTime start = new DateTime(1970,1,1);
			TimeSpan unix = initialValue.Subtract(start);
			this._value = Math.Ceiling(unix.TotalSeconds);
		}
		public static UnixTimestamp operator+(UnixTimestamp lhs, UnixTimestamp rhs)
		{
			return new UnixTimestamp(lhs + rhs);
		}
		public static UnixTimestamp operator-(UnixTimestamp lhs, UnixTimestamp rhs)
		{
			return new UnixTimestamp(lhs - rhs);
		}
		public static implicit operator UnixTimestamp(double Value)
		{
			return new UnixTimestamp(Value);
		}
		public static implicit operator UnixTimestamp(DateTime Value)
		{
			return new UnixTimestamp(Value);
		}
		public static implicit operator double (UnixTimestamp from)
		{
			return from.Value;
		}
		public static implicit operator int(UnixTimestamp from)
		{
			return System.Convert.ToInt32(from.Value);
		}
		public static implicit operator long(UnixTimestamp from)
		{
			return System.Convert.ToInt64(from.Value);
		}
			
		public override string ToString()
		{
			return this._value.ToString();
		}

		public DateTime ToDateTime()
		{
			DateTime dt = new DateTime(1970,1,1);
			dt.AddSeconds(this._value);
			return dt;
		}

		public static DateTime ToDateTime(double utimestamp)
		{
			DateTime dt = new DateTime(1970,1,1);
			dt.AddSeconds(utimestamp);
			return dt;
		}
		public static DateTime ToDateTime(UnixTimestamp ut)
		{
			return ToDateTime(ut);
		}
	}

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.