Showing posts with label DateTime. Show all posts
Showing posts with label DateTime. Show all posts

Tuesday, August 12, 2014

How to Parse datetime in multiple formats

Here is how we can parse different date formats get validated using one function.

In VB.NET

'''Validate method for Date format
  Private Function validateDate(ByVal strDate As String, ByVal strColumnName As String) As String
        Dim strError As String = ""
        Dim provider As CultureInfo = CultureInfo.GetCultureInfo("en-us")
        Dim formatStrings As String() = {"MM/dd/yyyy", "yyyy-MM-dd", "d"}
        Dim dateValue As DateTime
        Try
            If DateTime.TryParseExact(strDate, formatStrings, provider, DateTimeStyles.None, dateValue) Then
                strError = "Success"
            Else
                strError = "Failed"
            End If
        Catch ex As Exception

        End Try
        Return strError
    End Function

In C#

///Validate method for Date format
private string validateDate(string strDate, string strColumnName)
{
    string strError = "";
    CultureInfo provider = CultureInfo.GetCultureInfo("en-us");
    string[] formatStrings = {
        "MM/dd/yyyy",
        "yyyy-MM-dd",
        "d"
    };
    DateTime dateValue = default(DateTime);
    try {
        if (DateTime.TryParseExact(strDate, formatStrings, provider, DateTimeStyles.None, out dateValue)) {
            strError = "Success";
        } else {
            strError = "Failed";
        }

    } catch (Exception ex) {
    }
    return strError;
}

Add as many as formatters to the formatStrings array and use this funtion. Happy Coding ☺☻

Wednesday, June 05, 2013

How to Validate Date based on format “MM/dd/YYYY” in VB.NET

Here is the sample code snippet which I wrote to do date validation for a particular format and culture.

   1: Private Function validateDateFormat(ByVal strDate As String) As Boolean
   2:     Dim isValid As Boolean = True
   3:     Dim provider As CultureInfo = CultureInfo.GetCultureInfo("en-us")
   4:     Dim formats As String = "d" '"MM/dd/yyyy"
   5:     Dim dateValue As DateTime
   6:     Try
   7:         If DateTime.TryParseExact(strDate, formats, provider, DateTimeStyles.None, dateValue) Then
   8:             isValid = True
   9:         Else
  10:             isValid = False
  11:         End If
  12:     Catch ex As Exception
  13:  
  14:     End Try
  15:     Return isValid
  16: End Function


You can change the formats and CultureInfo to your own custom information. Here is my pervious blog which describes how formatting date time can be done using string object.

Saturday, September 10, 2011

Convert DateTime values to W3C DateTime format in C#

ConvertDateToW3CTime() function takes a C# DateTime value and converts it to a W3C formatted date/time value.
The function works by first converting the date/time parameter to a UTC (Coordinated Universal Time) value and formatting it. It then appends the UTC offset time to the previously formatted string.

The T placed between the date and time simply indicates that the numbers following it are Time values. The UTC offset can be one 3 states, zero e.g. there is not difference in time between the UTC value and the local value. A zero value is identified by simply appending the letter Z to the end of the formatted datetime value. If the offset time is greater than 0 then it is preceded with a + sign, e.g. 2 hours and 30 minutes over the UTC time would be written as +02:30. If the offset is less than the UTC value then it is preceded with a sign e.g. -01:00.

/// <summary>
/// Converts a datetime value to w3c format
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static string ConvertDateToW3CTime(DateTime date)
{
//Get the utc offset from the date value
var utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(date);
string w3CTime = date.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss");
//append the offset e.g. z=0, add 1 hour is +01:00
w3CTime += utcOffset == TimeSpan.Zero ? "Z" :
String.Format("{0}{1:00}:{2:00}", (utcOffset > TimeSpan.Zero ? "+" : "-")
, utcOffset.Hours, utcOffset.Minutes);

return w3CTime;
}



Here is an example, how to use it


ConvertDateToW3CTime(DateTime.Now);
//Output 2011-10-17T19:10:48+01:00

Monday, December 27, 2010

Get Current Year, Month and Future date

declare @fdate datetime
set @fdate = '12/20/2012'
-- current month, current year, fut date
-- you can change the date param with your choice
SELECT CAST(CAST(DATEPART(MONTH,GETDATE()) as varchar(2))+ '-' 
 + CAST( DATEPART(DAY,@fdate) as varchar(2)) +'-' 
 + CAST( DATEPART(YEAR,GETDATE()) as varchar(4)) as datetime) as newdate