String not recognized as a valid datetime [duplicate] - c#

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;

Related

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

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.

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";

Converting string that is dd.mm.yyyy. HH:mm:ss format to datetime C# [duplicate]

This question already has answers here:
Converting a String to DateTime
(17 answers)
Closed 3 years ago.
So I have string that is 24.08.2010. 21:21:21, I want to convert it to 2010-08-24 21:21:21 to be able to save it in the db.
I tried this
var input = "22.08.2010. 7:00:00";
var date = DateTime.ParseExact(input,"yy-MM-dd HH:mm:ss.fff", null);
Console.WriteLine(date);
but I get error:
System.FormatException: String was not recognized as a valid DateTime.
Anyone have idea how to convert this?
First, you need to convert string input into date:
var input = "22.08.2010. 7:00:00";
var date = DateTime.ParseExact(input, "dd.MM.yyyy. H:mm:ss", null);
And than convert date to string:
Console.WriteLine(date.ToString("yy-MM-dd HH:mm:ss"));

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

C# casting String to DateTime [duplicate]

This question already has an answer here:
Parsing ISO 8601 with timezone to .NET datetime
(1 answer)
Closed 9 years ago.
I want to cast in C# a String to DateTime.
My String contains: String input = "2012-07-31T00:00:00.000+0200"
and i used the following pattern: String datePattern = "yyyy-MM-dd%HH:mm:ss.fffz";
MyDateTime myDate = new DateTime();
MyDateTime myDate = DateTime.ParseExact(input, datePattern, null);
And i am getting the following error: String was not recognized as a valid DateTime.
Was pretty sure, because i am not sure how to solve this 'T'and which Timezone i should use.
There are three variants of it at the msdn side.
Which one i need to use, or can i create my own one?
Any suggestions?
You can use The "K" Custom Format Specifier with "yyyy-MM-ddTHH:mm:ss.FFFK" format like;
string s = "2012-07-31T00:00:00.000+0200";
var date = DateTime.ParseExact(s, "yyyy-MM-dd'T'HH:mm:ss.FFFK", CultureInfo.InvariantCulture);
Console.WriteLine(date);
Output will be;
7/30/2012 10:00:00 PM
Here a demonstration.
For more information take a look at;
Custom Date and Time Format Strings

Categories

Resources