Issue in Converting String to DateTime Format - c#

I am unable to convert the string values that has been extracted from the ddl to a DateTime datatype.
The Error Message
An exception of type 'System.FormatException' occurred in mscorlib.dll
but was not handled in user code. Additional information: String was
not recognized as a valid DateTime.
I only require the date to be updated in the SQL database.
This is the an image of the DataDictionary and the Attribute I require would be the birthdate
These are my current codes that get and convert the date time.
string birth = ddlDay.SelectedItem.Value + "-" + ddlMonth.SelectedItem.Value + "-" + ddlYear.SelectedItem.Value;
DateTime birthDate = DateTime.ParseExact(birth, "dd-MMMM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
objCustomer.birthDate = birthDate;

string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", dt.Year, dt.Month, dt.Day);

Instead of ParseExact you could use TryParse to be safe. ie:
var ddlDaySelectedItemValue = "29";
var ddlMonthSelectedItemValue = "Feb"; // February, 2, 02
var ddlYearSelectedItemValue = "2016";
DateTime birthDate;
string birth = ddlYearSelectedItemValue + " " + ddlMonthSelectedItemValue + " " + ddlDaySelectedItemValue;
if (DateTime.TryParse(birth, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate))
{
objCustomer.birthDate = birthDate;
}

Change your code to:
DateTime.ParseExact(birth, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);

Related

Combine date and time from string and convert to datetime

I have 2 strings (date(13/04/2021),time("06:30")) and I want to combine them together to datetime format and I am getting the below error.
System.FormatException: 'String was not recognized as a valid DateTime.'
What I am doing wrong?
if I change the tempdate format to "yyyy-dd-MM" I get the error there
var type = form["GymType"];
var time = form["states_ddl"];
var date = form["date2"];
var username = form["username"];
var numberofpersons = 0;
if (type == "2")
{
//gym
numberofpersons = 9;
}
else
{
//cross
numberofpersons = 5;
}
Booking toadd = new Booking();
var currenduser = User.Identity.GetUserId();
var tempdate = DateTime.ParseExact(date , "dd/MM/yyyy", CultureInfo.InvariantCulture);
DateTime d = DateTime.ParseExact(tempdate + " " + time, "yyyy-dd-MM HH:mm", CultureInfo.InvariantCulture);
What you do is convert de string to a dateTime 'tempdate', and than on the next line you convert it back to a string.
What i would do is convert the date as you do and parse the time separate, than add them together.
var tempdate = DateTime.ParseExact(date , "dd/MM/yyyy", CultureInfo.InvariantCulture);
var timspan = TimeSpan.Parse(time);
DateTime d = tempdate.Add(timspan);
You can use Convert to do this
var date = Convert.ToDateTime("13/04/2021 06:30");
try this
string d = "13/04/2021";
string t = "10:30PM";
string dateAndTime = d.Trim() + ' ' + t.Trim();
DateTime dt = DateTime.ParseExact(dateAndTime, "MM/dd/yyyy hh:mmtt",
CultureInfo.InvariantCulture, DateTimeStyles.None);
dt = DateTime.Parse(dateAndTime, CultureInfo.InvariantCulture,
DateTimeStyles.None);

System.FormatException: String was not recognized as a valid DateTime (DateTime Format yyyyMMdd:HHmmss)

I have a date time format of yyyyMMdd:HHmmss. I receive the datetime from a device and I can confirm that the format is yyyyMMdd:HHmmss.
For example I get datetime as 20180331:162308. I tried to convert to 03/31/2018 04:23 PM format by using below code:
string localDateTime =
Convert.ToString(protocol.GetParameter(Parameter.localmdmdatetimestr_3043));
string formatString = "yyyyMMdd:HHmmss";
protocol.Log(
"QA" + protocol.QActionID + "|DateTime|localDateTime" + localDateTime,
LogType.Error,
LogLevel.NoLogging);
DateTime LocalDt = DateTime.ParseExact(
localDateTime,
formatString,
CultureInfo.InvariantCulture);
But instead get
System.FormatException: String was not recognized as a valid DateTime
error.
As per your requirement
string localDateTime = Convert.ToString("20180331:162308");
string formatString = "yyyyMMdd:HHmmss";
DateTime LocalDt = DateTime.ParseExact(
localDateTime,
formatString, CultureInfo.InvariantCulture);
Console.WriteLine(LocalDt);
var test = LocalDt.ToString("yyyy/MM/dd HH:mm tt", CultureInfo.InvariantCulture);
Console.WriteLine(test);
Console.ReadLine();

How Do I Convert IANA zone + datetime to UTC + Offset using NodaTime

I have local time in string format: "yyyy-MM-dd HH:mm:ss" and an IANA Time Zone for that time (e.g. "Europe/London").
How do I convert that in C#, maybe using NodaTime, to a UTC+TimeZone Offset string
e.g. "yyyy-MM-dd HH:mm:ss+01:00" ?
I don't even know where to start!
This is as far as I get (I am afraid I'm new to C sharp):
I understand I need to convert it to an instant, but just can't get to grips with the library.
string dateTime = "2014-12-31 12:30:00";
string IANA = "Europe/London";
Instant instDateTime = NodaTime.Instant.FromDateTimeUtc(Convert.ToDateTime(dateTime));
string outputUTC = string.Format("yyyy-MM-dd HH:mm:ssZ", instDateTime);
Thanks to Matt (see answer below), I now have the functions I needed (Note that in the end what I needed was UTC and not date time + offset):
What is a little worrying is that is says that Europe/Moscow is UTC+04:00, whereas it is actually UTC+03:00 since 26 October 2014.
static void Main(string[] args)
{
string dateTime = "2014-12-31T12:30:00";
string timeZone = "Europe/Moscow";
Console.WriteLine(timeZone + " Local time '" + dateTime + "' to Zulu time");
Console.WriteLine(ConvertIANALocalTimeToZulu(timeZone, dateTime));
Console.WriteLine();
Console.WriteLine("Zulu time '" + dateTime + "' to " + timeZone + " local time");
Console.WriteLine(ConvertZuluTimeToIANALocalTime(timeZone, dateTime));
Console.ReadLine();
}
static string ConvertIANALocalTimeToZulu(string timeZoneIANA, string localDateTime)
{
var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-ddTHH:mm:ss");
LocalDateTime ldt = pattern.Parse(localDateTime).Value;
ZonedDateTime zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZoneIANA]);
Instant instant = zdt.ToInstant();
ZonedDateTime zulu = instant.InUtc();
////string output = zulu.ToString("yyyy-MM-dd HH:mm:sso<m>", CultureInfo.InvariantCulture);
string output = zulu.ToString("yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);
return output;
}
static string ConvertZuluTimeToIANALocalTime(string timeZoneIANA, string zuluDateTime)
{
var pattern = InstantPattern.CreateWithInvariantCulture("yyyy-MM-ddTHH:mm:ss");
Instant instant = pattern.Parse(zuluDateTime).Value;
ZonedDateTime zdt = instant.InZone(DateTimeZoneProviders.Tzdb[timeZoneIANA]);
////string output = zdt.ToString("yyyy-MM-dd HH:mm:sso<m>", CultureInfo.InvariantCulture);
string output = zdt.ToString("yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);
return output;
}
It's unclear from your question if you meant that the original value was in UTC or in local time.
If it's in UTC, then do the following:
string dateTime = "2014-12-31 12:30:00";
string timeZone = "Europe/London";
var pattern = InstantPattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss");
Instant instant = pattern.Parse(dateTime).Value;
ZonedDateTime zdt = instant.InZone(DateTimeZoneProviders.Tzdb[timeZone]);
string output = zdt.ToString("yyyy-MM-dd HH:mm:sso<m>", CultureInfo.InvariantCulture);
If it's in local time, then do this instead:
string dateTime = "2014-12-31 12:30:00";
string timeZone = "Europe/London";
var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss");
LocalDateTime ldt = pattern.Parse(dateTime).Value;
ZonedDateTime zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZone]);
string output = zdt.ToString("yyyy-MM-dd HH:mm:sso<m>", CultureInfo.InvariantCulture);
Also - you should note that in December, London is on GMT (UTC+00:00) - so the output of either function will be "2014-12-31 12:30:00+00:00" for the values you provided.

parseExactDate from UTC to specified cltureinfo

I'm trying to convert a date in format UTC "yyyy-MM-ddTHH:mmZ" to a localdatetime but when changing cultureInfo by fr-FR or other one, o keep always the same localdatetime
for example i do this:
IFormatProvider culture = new System.Globalization.CultureInfo("en-US",null);
DateTime tempDte= DateTime.MinValue;
string test = ""2014-04-09T14:29Z";
DateTime.TryParseExact(test , "yyyy-MM-ddTHH:mmZ", culture, DateTimeStyles.AssumeLocal, out tempDte)
Console.WriteLine("col = " + s + " &init " + test + " &ToLocalTime = " + tempDte.ToLocalTime() + " &ToUniversalTime = " + tempDte.ToUniversalTime());
Could you explain me how do this for having time depending on th eculture
Thanks
You don't have seconds part in your DateTime String
Try This:
DateTime.TryParseExact(test , "yyyy-MM-ddTHH:mmZ", culture,
DateTimeStyles.AssumeLocal, out validDate);
Note : Make sure you are printing the converted DateTime variable validDate

take time and append to date to make datetime?

Say I have the following:
string fromTime = "8:00am";
string someDate = "06/01/2012";
I want to end up doing this:
DateTime dt = Convert.ToDateTime(someDate + someTime);
Basically I want to take a date and add the time to it with the result for the above to be
06/01/2012 8:00am
But have it stored in a datetime variable. Is this possible?
You could use the DateTime.TryParseExact method which allows you to specify a format when parsing:
class Program
{
static void Main()
{
string s = "06/01/2012 8:00am";
string format = "dd/MM/yyyy h:mmtt";
DateTime date;
if (DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
Console.WriteLine(date);
}
}
}
Try this:
DateTime dt = DateTime.ParseExact(someDate + " " + someTime, "MM/dd/yyyy h:mmtt", CultureInfo.InvariantCulture);

Categories

Resources