Browsing all articles from January, 2011
Code Snippet 1: Best way to convert string to DateTime
This is the best way to convert string to Date
the following code convert string to date which is in
“d/M/yyyy” or “dd/MM/yyyy” or “d/MM/yyyy” or “dd/M/yyyy”
string MyDate = "12/12/2012";
DateTime _MyDate;
if (!DateTime.TryParseExact(MyDate, new[] { "d/M/yyyy", "dd/MM/yyyy", "d/MM/yyyy", "dd/M/yyyy" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out _MyDate))
{
this._message = "Invalid Date";
// do here with invalid date
}
_MyDate
// do here with valid date
DateTime _MyDate;
if (!DateTime.TryParseExact(MyDate, new[] { "d/M/yyyy", "dd/MM/yyyy", "d/MM/yyyy", "dd/M/yyyy" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out _MyDate))
{
this._message = "Invalid Date";
// do here with invalid date
}
_MyDate
// do here with valid date
Function:
public static bool ToDate(string DateString, out DateTime Date)
{
if (!DateTime.TryParseExact(DateString, new[] { "d/M/yyyy", "dd/MM/yyyy", "d/MM/yyyy", "dd/M/yyyy" }, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out Date))
return false;
return true;
}
{
if (!DateTime.TryParseExact(DateString, new[] { "d/M/yyyy", "dd/MM/yyyy", "d/MM/yyyy", "dd/M/yyyy" }, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out Date))
return false;
return true;
}
Remove duplicates in a string array
These are the followings ways, where we can filter a string array to remove the duplicates.
private static string PreviousItem;
private static bool Match(string item)
{
bool result = (item == PreviousItem);
PreviousItem = item;
return result;
}
public static string[] NoDuplicates(string[] input)
{
PreviousItem = null;
List<string> result = new List<string>(input);
result.Sort();
result.RemoveAll(Match);
return result.ToArray();
}
private static bool Match(string item)
{
bool result = (item == PreviousItem);
PreviousItem = item;
return result;
}
public static string[] NoDuplicates(string[] input)
{
PreviousItem = null;
List<string> result = new List<string>(input);
result.Sort();
result.RemoveAll(Match);
return result.ToArray();
}
Categories
- Dot Net (12)
- .Net Framework (1)
- Ajax (1)
- ASP.NET (6)
- C#.NET (3)
- Code Snippets (3)
- WCF (1)
- SQL Server (3)
- Tutorials (1)
- Video (1)




