Created
October 20, 2011 19:49
-
-
Save jonathascosta/1302134 to your computer and use it in GitHub Desktop.
Classe Competência para lidar com mês/ano
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Competencia | |
{ | |
public Competencia(int mes, int ano) | |
{ | |
try | |
{ | |
new DateTime(ano, mes, 1); | |
} | |
catch (Exception) | |
{ | |
throw new ArgumentException(string.Format("Mês/Ano inválido(s). ({0}/{1})", mes, ano)); | |
} | |
this.Ano = ano; | |
this.Mes = mes; | |
} | |
public Competencia(DateTime data) | |
{ | |
this.Mes = data.Month; | |
this.Ano = data.Year; | |
} | |
public int Mes { get; set; } | |
public int Ano { get; set; } | |
public DateTime PrimeiroDia { get { return new DateTime(Ano, Mes, 1); } } | |
public DateTime UltimoDia { get { return this.PrimeiroDia.AddMonths(1).AddDays(-1); } } | |
public Competencia Anterior { get { return new Competencia(this.PrimeiroDia.AddMonths(-1)); } } | |
public Competencia Proxima { get { return new Competencia(this.PrimeiroDia.AddMonths(1)); } } | |
public override string ToString() | |
{ | |
return this.PrimeiroDia.ToString("MM/yyyy"); | |
} | |
public override bool Equals(object obj) | |
{ | |
Competencia compareTo = obj as Competencia; | |
if (ReferenceEquals(this, compareTo)) | |
return true; | |
return (compareTo != null) && (this.Mes == compareTo.Mes) && (this.Ano == compareTo.Ano); | |
} | |
public override int GetHashCode() | |
{ | |
return this.Ano * 12 + this.Mes; | |
} | |
#region Operadores | |
public static bool operator <(Competencia c1, Competencia c2) | |
{ | |
return c1.PrimeiroDia < c2.PrimeiroDia; | |
} | |
public static bool operator >(Competencia c1, Competencia c2) | |
{ | |
return c1.PrimeiroDia > c2.PrimeiroDia; | |
} | |
public static bool operator ==(Competencia c1, Competencia c2) | |
{ | |
return c1.PrimeiroDia == c2.PrimeiroDia; | |
} | |
public static bool operator !=(Competencia c1, Competencia c2) | |
{ | |
return c1.PrimeiroDia != c2.PrimeiroDia; | |
} | |
#endregion | |
} | |
public static class CompetenciaExtensions | |
{ | |
public static Competencia ToCompetencia(this DateTime data) | |
{ | |
return new Competencia(data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment