Last active
August 31, 2015 08:32
-
-
Save fcojperez/cfc0ab92a3e3aebc6838 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
/* | |
* Snippet para la conversión de fechas en tipo String a DateTime | |
* 31/08/2015, Francisco Pérez, [email protected] | |
*/ | |
namespace ConsoleApplication1 | |
{ | |
class ConvertString2DateTime | |
{ | |
static void Main(string[] args) | |
{ | |
ConvertString2DateTime p = new ConvertString2DateTime(); | |
/* | |
* Comprobación de conversión | |
*/ | |
p.testConvertDateTime(); | |
} | |
/** | |
* String2DateTime: convierte la fecha de tipo String con formato YYYY-MM-DD HH:mm:ss.sss a Date time para formato Español | |
* 31/08/2015, Francisco Pérez, [email protected] | |
* @Parameters | |
* strDateTime = fecha en formato YYYY-MM-DD HH:mm:ss.sss | |
* @return DateTime | |
*/ | |
DateTime String2DateTime(String strDateTime) { | |
DateTime dt; | |
String strTempDateTime; | |
//Comprobamos si el separador de milisegundos es una coma y lo sustituimos por un punto. | |
if (strDateTime.IndexOf(",") > 0) | |
{ | |
strTempDateTime = strDateTime.Replace(",", "."); | |
} | |
else { | |
strTempDateTime = strDateTime; | |
} | |
//Definimos como cultura el español | |
IFormatProvider culture = new System.Globalization.CultureInfo("es-ES", true); | |
dt = DateTime.Parse(strTempDateTime, culture, System.Globalization.DateTimeStyles.AssumeLocal); | |
return dt; | |
} | |
void testConvertDateTime() { | |
System.Console.WriteLine("**********************************************"); | |
System.Console.WriteLine("* CONVERSION DATATIME TO STRING *"); | |
System.Console.WriteLine("**********************************************"); | |
ConvertString2DateTime p = new ConvertString2DateTime(); | |
String strDT1 = "2015-08-21 04:30:00,205"; | |
System.Console.WriteLine("Caso 1: " + strDT1); | |
System.Console.WriteLine(p.String2DateTime(strDT1)); | |
String strDT2 = "2015-08-21 04:30:00.205"; | |
System.Console.WriteLine("Caso 2: " + strDT2); | |
System.Console.WriteLine(p.String2DateTime(strDT2)); | |
String strDT3 = "2015-08-21 04:30:00"; | |
System.Console.WriteLine("Caso 2: " + strDT3); | |
System.Console.WriteLine(p.String2DateTime(strDT3)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment