How can i convert a string to date time in c#? [duplicate] - c#

This question already has answers here:
Converting a String to DateTime
(17 answers)
Closed 1 year ago.
I have a string returned from an api call .
The string is : 11/25/2021 05:20:21
Now that is a mm/dd/yyyy hh:mm:ss
I want to compare it to the datetime 2021-11-25 05:03:17.667
I do the following:
var dt1="11/25/2021 05:20:21";
var dt2= "2021-11-25 05:03:17.667"
DateTime date1 = Convert.ToDateTime(dt1);
DateTime date2 = Convert.ToDateTime(dt2);
int result = DateTime.Compare(date1, date2);
if (result < 0)
{
//d1 is earlier than d2.
}
but when i do the call DateTime date2 = Convert.ToDateTime(dt2); it gives an error , string is not in the correct format ?

You should probably use DateTime.ParseExact, which allows you to provide an excat format to parse your string.

Related

How to make formatException gone in Datetime [duplicate]

This question already has answers here:
Convert string to DateTime in c#
(3 answers)
DateTime.Parse throw exception in C#
(1 answer)
DateTime.Parse throwing format exception
(3 answers)
Closed 2 years ago.
Hi I just want to know how to make formatException gone when I'm inserting Datetime.
coding is in down below:
DateTime dob = Convert.ToDateTime(z);
dob.ToString("yyMMdd");
DateTime today = DateTime.Today;
today.ToString("yyMMdd");
var year = today.Year - dob.Year;
age = Convert.ToString(year);
return a;
Try use DateTime.TryParse or DateTime.TryParseExact to check your datetime string and store to your variable after parse at the same time
Use the DateTime.ParseExact() method to convert your date string z to a DateTime value -
var z = "23/09/2020";
DateTime dob = DateTime.ParseExact(z, "dd/MM/yyyy", null);
As you can see, you have to pass the date format you are trying to convert to the second parameter of the ParseExact() method as a string;

Convert a formmated string (dd/mm/yy) to and ISO datetime [duplicate]

This question already has answers here:
Converting a String to DateTime
(17 answers)
Closed 3 years ago.
I have a string variable named ProjectDateSigned which have this format 13/10/2019 23:00:00, and I need to convert it to ISO standard as follow 2019-10-13T23:00:00Z, so how I can do so? i am following the UK time local.
DateTime ISOdatetimeCustom = i["ProjectDateSinged"];
ParseExact to DateTime and then format ToString back:
string source = "13/10/2019 23:00:00";
string result = DateTime
.ParseExact(source, "d'/'M'/'yyyy' 'H':'m':'s", CultureInfo.InvariantCulture)
.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
If you already have a DateTime (i.e. if i["ProjectDateSinged"] returns DateTime), just format it:
string result = i["ProjectDateSinged"].ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
This should do the trick.
string myDate = "13/10/2019 23:00:00";
if (DateTime.TryParse(myDate, out var convertedDate))
{
string output = convertedDate.ToString("yyyy-MM-ddTHH:mm:ssZ");
}
If you don't want to do date/time conversions you can split and re-join the string:
var bits = i["ProjectDateSinged"].Split('/', ' ');
string newFormat = $"{bits[2]}-{bits[1]}-{bits[0]}T{bits[3]}Z";

String not recognized as a valid datetime [duplicate]

This question already has answers here:
String was not recognized as a valid DateTime
(3 answers)
Closed 4 years ago.
I just want to get the number of days from the FromDate to the ToDate:
string dt_now = DateTime.Now.ToString("m/d/yyyy");
num_days = (Convert.ToDateTime(dt_now) - Convert.ToDateTime(dr4.GetString(13))).Days;
dr4.GetString(13) is from the database with the same format as m/d/yyyy
Sample data for dr4.GetString(13):
3/20/2018
1/19/2013
2/28/2013
3/19/2014
2/22/2017
10/6/2017
But I am getting an error:
String not recognized as a valid DateTime
How should I properly do it?
Rather than using string to represent date formats, better to store date values as datetime data type in your database and use DataReader.GetDateTime() to retrieve it:
// common usage
num_days = (DateTime.Now - dr4.GetDateTime(13)).Days;
// alternative with Subtract()
num_days = DateTime.Now.Subtract(dr4.GetDateTime(13)).Days;
For current state, use this code:
var date = DateTime.ParseExact(dr4.GetString(13).Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
num_days = DateTime.Now.Subtract(date).Days;
Can you not simply do this:
var provider = CultureInfo.InvariantCulture;
var format = "M/d/yyyy";
var d2 = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine(" Days: {0,3}", (DateTime.Now - d2).Days);
Reference here: https://learn.microsoft.com/en-us/dotnet/api/system.timespan.totaldays?view=netframework-4.7.2
you can use the Timespan class like this:
string dr4 = "10/2/2018";
TimeSpan duration = DateTime.Now.Subtract(DateTime.Parse(dr4, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal));
int result = duration.Days;

How to convert number into dd/mm/yyyy format in c#? [duplicate]

This question already has answers here:
How do I format a DateTime in a different format?
(2 answers)
Closed 5 years ago.
Suppose I have string "20171013", Now I want to convert it into 13-10-2017 which should also be in the string. Also, I have stored these string in a property of the list. Is it possible to convert all of those string numbers of property using foreach loop?
This is the code I'm working on
calendarResponse.AgendaOptions
.ForEach(a => a.AppointmentDate =
DateTime.ParseExact(a.AppointmentDate, "ddMMyyyy",
CultureInfo.InvariantCulture).ToString());
Here, AppointmentDate has date in string format like "20171013"
I got error:
DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar
Reason for error is that the correct format should be yyyyMMdd and not ddMMyyyy. Also apply formatting in ToString to get desired output format:
var data = new List<string> { "20171013" };
var result = data.Select(item => DateTime.ParseExact(item, "yyyyMMdd", CultureInfo.InvariantCulture)
.ToString("dd-MM-yyyy", CultureInfo.InvariantCulture)).ToList();
For given code:
calendarResponse.AgendaOptions.ForEach(a =>
a.AppointmentDate = DateTime.ParseExact(a.AppointmentDate, "yyyyMMdd", CultureInfo.InvariantCulture)
.ToString("dd-MM-yyyy", CultureInfo.InvariantCulture));
For the supported DateTime formats see documentation
another way to do is like this
string s = "20171013";
string year = s.Substring(0,4);
string month = s.Substring(4, 2);
string day = s.Substring(6, 2);
string date = day+'-'+month+'-'+year;
Console.WriteLine(date);
result 13-10-2017

Convert string(dd/MM/yyyy hh:mm) to datetime format [duplicate]

This question already has answers here:
Converting a String to DateTime
(17 answers)
Closed 8 years ago.
I have string with datetime format dd/MM/yyyy hh:mm.I want to calculate duration between two dates but failed to get datetime in correct format.please help.
thanks in advance
After parsing date string create two dates.
DateTime date1 = new DateTime();
DateTime date2 = new DateTime();
date1 = DateTime.Parse("22/05/2013 09:50:00");
date2 = DateTime.Parse("22/05/2014 09:50:00");
Then use TimeSpan structure to calculate interval:
TimeSpan ts_interval = date2 - date1;
You can use the following properties:
ts_interval.TotalSeconds;
ts_interval.TotalMinutes;
ts_interval.TotalHours;
For more visit http://msdn.microsoft.com/en-us/library/system.timespan_properties%28v=vs.110%29.aspx
you can use build in method
DateTime.Parse("12/05/1999 18:25");
you can also check this post

Categories

Resources