String to DateTime
Convert String to DateTime
In .Net, you can work with date and time easy with the DateTime class. You can use the methods like Convert.ToDateTime(String), DateTime.Parse() and DateTime.ParseExact() methods for converting a string-based date to a System.DateTime object.
Convert.ToDateTime(String)
This method will converts the specified string representation of a date and time to an equivalent date and time value
C#VB.Netstring iDate = "05/05/2005";
DateTime oDate = Convert.ToDateTime(iDate);
MessageBox.Show(oDate.Day + " " + oDate.Month + " " + oDate.Year );
Dim iDate As String = "05/05/2005"
Dim oDate As DateTime = Convert.ToDateTime(iDate)
MsgBox(oDate.Day & " " & oDate.Month & " " & oDate.Year)
DateTime.Parse()
DateTime.Parse method supports many formats. It is very forgiving in terms of syntax and will parse dates in many different formats. That means, this method can parse only strings consisting exactly of a date/time presentation, it cannot look for date/time among text.
C#VB.Netstring iDate = "2005-05-05";
DateTime oDate = DateTime.Parse(iDate);
MessageBox.Show(oDate.Day + " " + oDate.Month + " " + oDate.Year);
Dim iDate As String = "2005-05-05"
Dim oDate As DateTime = DateTime.Parse(iDate)
MsgBox(oDate.Day & " " & oDate.Month & " " & oDate.Year)
DateTime.ParseExact()
ParseExact method will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. The format of the string representation must match the specified format exactly.
C#VB.Netstring iString = "2005-05-05 22:12 PM";
DateTime oDate = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt",null);
MessageBox.Show(oDate.ToString());
Dim iString As String = "2005-05-05 22:12 PM"
Dim oDate As DateTime = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt", Nothing)
MsgBox(oDate.ToString())
The null(Nothing) parameter is the CultureInfo object that corresponds to the current culture is used.
CultureInfo
When numbers, dates and times are formatted into strings or parsed from strings then a culture (CultureInfo)is used to determine how it is done. If you know what specific culture that your dates and decimal or currency values will be in ahead of time, you can use that specific CultureInfo property, e.g. CultureInfo("en-US").
The CultureInfo.InvariantCulture property is neither a neutral nor a specific culture. It is a third type of culture that is culture-insensitive. It is associated with the English language but not with a country or region.
C#VB.Netstring iString = "2005-05-05 22:12 PM";
DateTime oDate = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt", System.Globalization.CultureInfo.InvariantCulture);
MessageBox.Show(oDate.ToString());
Dim iString As String = "2005-05-05 22:12 PM"
Dim oDate As DateTime = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt", System.Globalization.CultureInfo.InvariantCulture)
MsgBox(oDate.ToString())
DateTime.TryParse method
DateTime.TryParse converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.
public static bool TryParse(
string s,
out DateTime result
)
This method is similar to the DateTime.Parse(String) method, except that the TryParse(String, DateTime) method does not throw an exception if the conversion fails. Also, this method tries to ignore unrecognized data, if possible, and fills in missing month, day, and year information with the current date. The TryParse method is culture dependent so be very careful if you decide use it.
using System;
using System.Windows.Forms;
using System.Globalization;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string inString = "05/01/2009 06:32:00";
DateTime dateValue;
if (DateTime.TryParse(inString, out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", inString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", inString);
}
}
}
Looking for a .Net job ?
There are lot of opportunities from many reputed companies in the world. Chances are you will need to prove that you know how to work with .Net Programming Language. These .Net Interview Questions have been designed especially to get you acquainted with the nature of questions you may encounter during your interview for the subject of .Net Programming. Here's a comprehensive list of .Net Interview Questions, along with some of the best answers. These sample questions are framed by our experts team who trains for .Net training to give you an idea of type of questions which may be asked in interview.
Go to... .Net Interview Questions
How to to set datetime object to null ?
By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. More about..... Datetime object to null
How to find date difference ?
A calculation using a DateTime structure, such as Add or Subtract, does not modify the value of the structure. Instead, the calculation returns a new DateTime structure whose value is the result of the calculation. The DateTime.Substract method may be used in order to find the date-time difference between two instances of the DateTime method. More about..... Find date difference
DateTimePicker Control
The DateTimePicker control has two parts, a label that displays the selected date and a popup calendar that allows users to select a new date. The most important property of the DateTimePicker is the Value property, which holds the selected date and time. More about..... DateTimePicker
- What is the root class in .Net
- How to set DateTime to null in C#
- How to convert string to integer in C#
- What's the difference between String and string in C#
- What is the best way to iterate over a Dictionary in C#?
- How to convert a String to byte Array in c#
- Detecting arrow keys in winforms C# and vb.net
- how to use enum with switch case c# vb.net
- Passing Data Between Windows Forms C# , VB.Net
- How to Autocomplete TextBox ? C# vb.net
- Autocomplete ComboBox c# vb.net
- How to convert an enum to a list in c# and VB.Net
- How to Save the MemoryStream as a file in c# and VB.Net
- How to parse an XML file using XmlReader in C# and VB.Net
- How to parse an XML file using XmlTextReader in C# and VB.Net
- Parsing XML with the XmlDocument class in C# and VB.Net
- How to check if a file exists in C# or VB.Net
- What is the difference between Decimal, Float and Double in .NET? Decimal vs Double vs Float
- How to Set ComboBox text and value - C# , VB.Net
- How to sort an array in ascending order , sort an array in descending order c# , vb.net
- Convert Image to Byte Array and Byte Array to Image c# , VB.Net
- How do I make a textbox that only accepts numbers ? C#, VB.Net, Asp.Net
- What is a NullReferenceException in C#?
- How to Handle a Custom Exception in C#
- Throwing Exceptions - C#
- Difference between string and StringBuilder | C#
- How do I convert byte[] to stream C#
- Remove all whitespace from string | C#
- How to remove new line characters from a string in C#
- Remove all non alphanumeric characters from a string in C#
- What is character encoding
- How to Connect to MySQL Using C#
- How convert byte array to string C#
- What is IP Address ?
- Run .bat file from C# or VB.Net
- How do you round a number to two decimal places C# VB.Net Asp.Net
- How to break a long string in multiple lines
- How do I encrypting and decrypting a string asp.net vb.net C# - Cryptography in .Net
- Type Checking - Various Ways to Check datatype of a variable typeof operator GetType() Method c# asp.net vb.net
- How do I automatically scroll to the bottom of a multiline text box C# , VB.Net , asp.net
- Difference between forEach and for loop
- How to convert a byte array to a hex string in C#?
- How to Catch multiple exceptions with C#