How to convert a Datetime String into a Datetime object - c#

string DateCreated = "2012-05-24 12:34:40.060"; USA culture
How do I create the string into a Date time object with a format that include the month,
day, year, hour, minutes, seconds, milliseconds.
I think the format is this "MM/dd/yyyy hh:mm:ss.fff tt" but not sure.
** ** = underline in red, its an error
I need the datetime object because I want to pass it through another function that only accept a value of "DateTime" and not a string
Any help would be appreciated.
Thank You
this is what I have so far but i know its wrong
string DateCreated = "2012-05-24 12:34:40.060";
DateTime dt = **new DateTime(DateCreated);**
DateTime dateCreated = **dateCreated.ToString("MM/dd/yyyy hh:mm:ss.fff tt")**;

var dateTime = DateTime.ParseExact(DateCreated, "yyyy-MM-dd HH:mm:ss.fff");

string dateCreated = "2012-05-24 12:34:40.060";
DateTime myDate = DateTime.ParseExact(dateCreated, "yyyy-MM-dd HH:mm:ss.fff",
System.Globalization.CultureInfo.InvariantCulture)
you can also use
Convert.ToDateTime Method (String)

Related

How can I convert this date "03/01/2018 12:00 AM" to "2018-03-01" in C#?

I am using this code to convert a date 03/01/2018 12:00 AM to 2018-03-01 in C#:
DateTime startDate = DateTime.ParseExact(TextBox1.Text.ToString(),
"yyyy-mm-dd",
System.Globalization.CultureInfo.InvariantCulture);
but it throws an exception
String was not recognized as valid datetime
This Will Work Like A Charm
string bs = "03/01/2018 12:00 AM";
String startDate = DateTime.ParseExact(bs,"MM/dd/yyyy hh:mm tt",System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
Console.WriteLine(startDate);
// Outputs 2018-03-01
You can verify the code here
A DateTime represents a particular point in time. ParseExact is a way of turning a string into a DateTime. By saying ParseExact with "yyyy-mm-dd" you are telling it that the string you are giving it begins with a four digit year, which it doesn't. Fix the format string that you are supplying so that the parse works.
Once you have the value in your DateTime variable, you can use ToString("yyyy-mm-dd") to turn that DateTime back into a string.
Remove AM from your Textbox and edit format string, then your sample code will work.
This line run successfully :
DateTime startDate = DateTime.ParseExact("03/01/2018 12:00", "MM/dd/yyyy hh:mm", System.Globalization.CultureInfo.InvariantCulture);
string inputDate = "03/01/2018 12:00 AM";
string outputDate = DateTime.Parse(inputDate).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);

Parse string to DateType ASP.NET C# exception - The string was not recognized as a valid DateTime

So I have a date which is in this format. My goal is to add 7 days to this string startdate and post it into a database as a string. However, I have to convert it to datetime to allow me to add days to it. I am reading startdate from a database but this is what it looks like.
string startdate = "10-03-2018 03:15PM";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime starttime2 = DateTime.ParseExact(startdate, "MM/dd/yyyy HH:mm tt", culture);
// It is breaking on the above line with the error - The string was not recognized as a valid DateTime.
DateTime endtime2 = starttime2.AddDays(+7);
Anyone able to help me solve this issue? I am new to C# and would appreciate any help at all..
Thank you
You have specified wrong format actually. You should be specifying the following format:
"dd-MM-yyyy hh:mmtt"
as your date is in format :
"10-03-2018 03:15PM"
Assuming that the first number us for day and second is for month, otherwise you can swap those.
You can see more details on the usage of ParseExact here.
Try this:
string startdate = "10-03-2018 03:15PM";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime starttime2 = DateTime.ParseExact(startdate, "dd-MM-yyyy hh:mmtt", culture);
no space between mm and tt. also this is 12 hours format so hh
I think this will help you
public static DateTime AddDaysToMyDate(string date)
{
return DateTime.ParseExact(date, "dd-MM-yyyy hh:mmtt", new CultureInfo("en-US", true)).AddDays(7);
}
Use it as
DateTime newDateTime = AddDaysToMyDate("10-03-2018 03:15PM");

Join date and time in c#

I have a win form c# SQL app that stores date in one column and time in the another.
There is only one date time picker on my form and I want to display both date and time values (which are from two separate columns)..
So far this is what I've done
Datetime final = datetime. Parse exact (date + " " + time , "MM/dd/yyyy hh:mm tt", cultureinfo. Invariant culture);
But it throws " string was not recognized as valid datetime" exception on the above line.
If date and time are DateTime variables, you can combine them with date arithmetic:
DateTime date=...;
DateTime time = ...;
DateTime finalDate = date.Date + time.TimeOfDay;
If they are strings, you can parse them to DateTime and TimeSpan variables:
DateTime date=DateTime.ParseExact(dateString,dateFormat,CultureInfo.InvariantCulture);
TimeSpan time = TimeSpan.ParseExact(timeString,timeFormat,CultureInfo.InvariantCulture);
DateTime finalDate = date.Date + time;
This is possible because you can add a DateTime and a TimeSpan value to get a new DateTime value
You can use TimeSpan.Parse to parse
DateTime newDateTime = date.Add(TimeSpan.Parse(time));
string d = DateTime.Now.Date.ToString("dd/MM/yyyy");
string t = DateTime.Now.ToString("h:mm");
var ts = TimeSpan.ParseExact(t, #"h\:mm",CultureInfo.InvariantCulture);
DateTime result = DateTime.ParseExact(d, "dd/MM/yyyy", CultureInfo.InvariantCulture)+ts;
Hope this helps,
Thanks.

c# String to DateTime in c#

I have following string stored in datatable's column with varchar or string datatype
"4/29/2013 9:00:00 PM"
Now i want to convert this string to datetime
Or
let me make more clear
I just want to extract time part from this string "4/29/2013 9:00:00 PM"
and store it in Database.
Please help me.
Thanks in advance
// String to DateTime
String MyString;
MyString = "4/29/2013 9:00:00 PM";
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "M/dd/yyyy hh:mm:ss tt",
null);
this should work for you.
Ok so this is a fairly simple operation you can use DateTime date = DateTime.Parse(dbString) and then use date.ToString("hh:mm tt") To get just the time and AM/PM. in the form "09:00 PM"
'hh' stands for the hours 01 to 12,
'mm' stands for the minutes 00 to 59,
'tt' stands for AM/PM
You could also use date.ToString("h:mm tt") to get the form "9:00 PM".
DateTime yourDateTime = DateTime.ParseExact(dateString, "MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);
Try this :
string myDateTimeString = "4/29/2013 9:00:00 PM";
DateTime myDateTime = DateTime.Parse(myDateTimeString);
string myTimeString = myDateTime.Date.ToString("hh:mm tt");
Hope this helps!
Time part of string in SQL :
select DATEPART(HOUR , cast('4/29/2013 9:00:00 PM' as datetime) ) as hr
, DATEPART(MINUTE , cast('4/29/2013 9:00:00 PM' as datetime) ) as minute
, DATEPART(SECOND , cast('4/29/2013 9:00:00 PM' as datetime) ) as sec
Or try this ext:
public static class Ext
{
public static string AsLocaleDateString(this DateTime dt)
{
var format = Thread.CurrentThread.CurrentUICulture.DateTimeFormat;
return dt.ToString(format.ShortDatePattern);
}
public static DateTime? AsLocaleDate(this string str)
{
if (str.IsNullEmpty())
{
return null;
}
var format = Thread.CurrentThread.CurrentUICulture.DateTimeFormat;
return DateTime.ParseExact(str, format.ShortDatePattern, CultureInfo.InvariantCulture, DateTimeStyles.None);
}
}

String to DateTime conversion as per specified format

I would like to have my end result in date format as per the specified format i.e YYMMDD how can i get this from a string given as below
string s="110326";
From string to date:
DateTime d = DateTime.ParseExact(s, "yyMMdd", CultureInfo.InvariantCulture);
Or the other way around:
string s = d.ToString("yyMMdd");
Also see this article: Custom Date and Time Format Strings
DateTime dateTime = DateTime.ParseExact(s, "yyMMdd", CultureInfo.InvariantCulture);
although id recommend
DateTime dateTime;
if (DateTime.TryParseExact(s, "yyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dateTime))
{
// Process
}
else
{
// Handle Invalid Date
}
To convert DateTime to some format, you could do,
string str = DateTime.Now.ToString("yyMMdd");
To convert string Date in some format to DateTime object, you could do
DateTime dt = DateTime.ParseExact(str, "yyMMdd", null); //Let str="110719"

Categories