DateTime formatting error? - c#

I want to compare dates. One date will be hard coded other will be picked from system.
My code is giving formatting error in this line:
string iStringdate = "05-05-2015";
DateTime oDate = DateTime.ParseExact(iStringdate, "dd-mm-yyyy", null);
Complete code:
private void button1_Click(object sender, EventArgs e)
{
string iStringdate = "05-05-2015";
DateTime oDate = DateTime.ParseExact(iStringdate, "dd-mm-yyyy", null);
//MessageBox.Show(oDate.ToString());
string iStringtime = "10:12 pm";
DateTime oTime = DateTime.ParseExact(iStringtime, "HH:mm tt", null);
//MessageBox.Show(oTime.ToString());
DateTime time = DateTime.Now;
DateTime date = DateTime.Today;
if (oDate < date)
{
Console.WriteLine("successfull");
}
else {
Console.WriteLine("fail");
}
}
Also how can I just get the system date and not the system time along with it?
Where am I wrong?

"mm" stands for minutes while "MM" means months.
DateTime.ParseExact(iStringdate, "dd-MM-yyyy", null);
Click here for a complete list of date formatting options.
And DateTime.Now returns the date and time, while DateTime.Today returns the current date and 00:00:00 as time.

Related

String was not recognized as a valid DateTime in asp.net core 3

The date format in an excel upload is returning this error.
{"String '6/3/2020 12:00:00 AM' was not recognized as a valid DateTime."}
I was able to fix the issue before here on stackoverflow(Check code) but today while testing the upload again, the problem persists. I have checked almost all the suggestions available on StackOverflow but none seem to be working.
On the excel sheet I have 6/3/2020 but in the code I got 6/3/2020 12:00:00 AM
I have been trying to fix this all day
for (int i = 2; i <= noOfRow; i++) //start from the second row
{
if (!string.IsNullOrEmpty(workSheet.Cells[i, 3].Text))
{
var date = workSheet.Cells[i, 3].Value.ToString();
//will throw exception if the fields in tenor are invalid
try
{
DateTime d = DateTime.ParseExact(date, "M/d/yyyy HH:mm tt", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
validationResult.Message = "Invalid Date.";
validationResult.IsValid = false;
validationResult.ErrorRowIndex = row;
logger.Error(validationResult.Message);
break;
}
}
else
{
validationResult.Message = "Empty Date.";
validationResult.IsValid = false;
validationResult.ErrorRowIndex = row;
logger.Error(validationResult.Message);
break;
}
++row;
}
return validationResult;
}
OK, here's your line of code:
DateTime d = DateTime.ParseExact(date, "M/d/yyyy HH:mm tt", CultureInfo.InvariantCulture);
And here is the date string you are trying to convert:
"6/3/2020 12:00:00 AM"
Notice how the date string contains hours, minutes, and seconds, but your format string only has hours and minutes. DateTime.ParseExact needs you to supply the exact format of the incoming string.
Try add seconds to format of date:
Replace
DateTime d = DateTime.ParseExact(date, "M/d/yyyy hh:mm tt", CultureInfo.InvariantCulture);
with
DateTime d = DateTime.ParseExact(date, "M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

How to convert a string to DateTime in a TextBox of a gridview [duplicate]

How do you convert a string such as 2009-05-08 14:40:52,531 into a DateTime?
Since you are handling 24-hour based time and you have a comma separating the seconds fraction, I recommend that you specify a custom format:
DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture);
You have basically two options for this. DateTime.Parse() and DateTime.ParseExact().
The first is very forgiving in terms of syntax and will parse dates in many different formats. It is good for user input which may come in different formats.
ParseExact 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. This way, you can easily detect any deviations from the expected data.
You can parse user input like this:
DateTime enteredDate = DateTime.Parse(enteredString);
If you have a specific format for the string, you should use the other method:
DateTime loadedDate = DateTime.ParseExact(loadedString, "d", null);
"d" stands for the short date pattern (see MSDN for more info) and null specifies that the current culture should be used for parsing the string.
try this
DateTime myDate = DateTime.Parse(dateString);
a better way would be this:
DateTime myDate;
if (!DateTime.TryParse(dateString, out myDate))
{
// handle parse failure
}
Use DateTime.Parse(string):
DateTime dateTime = DateTime.Parse(dateTimeStr);
Nobody seems to implemented an extension method. With the help of #CMS's answer:
Working and improved full source example is here: Gist Link
namespace ExtensionMethods {
using System;
using System.Globalization;
public static class DateTimeExtensions {
public static DateTime ToDateTime(this string s,
string format = "ddMMyyyy", string cultureString = "tr-TR") {
try {
var r = DateTime.ParseExact(
s: s,
format: format,
provider: CultureInfo.GetCultureInfo(cultureString));
return r;
} catch (FormatException) {
throw;
} catch (CultureNotFoundException) {
throw; // Given Culture is not supported culture
}
}
public static DateTime ToDateTime(this string s,
string format, CultureInfo culture) {
try {
var r = DateTime.ParseExact(s: s, format: format,
provider: culture);
return r;
} catch (FormatException) {
throw;
} catch (CultureNotFoundException) {
throw; // Given Culture is not supported culture
}
}
}
}
namespace SO {
using ExtensionMethods;
using System;
using System.Globalization;
class Program {
static void Main(string[] args) {
var mydate = "29021996";
var date = mydate.ToDateTime(format: "ddMMyyyy"); // {29.02.1996 00:00:00}
mydate = "2016 3";
date = mydate.ToDateTime("yyyy M"); // {01.03.2016 00:00:00}
mydate = "2016 12";
date = mydate.ToDateTime("yyyy d"); // {12.01.2016 00:00:00}
mydate = "2016/31/05 13:33";
date = mydate.ToDateTime("yyyy/d/M HH:mm"); // {31.05.2016 13:33:00}
mydate = "2016/31 Ocak";
date = mydate.ToDateTime("yyyy/d MMMM"); // {31.01.2016 00:00:00}
mydate = "2016/31 January";
date = mydate.ToDateTime("yyyy/d MMMM", cultureString: "en-US");
// {31.01.2016 00:00:00}
mydate = "11/شعبان/1437";
date = mydate.ToDateTime(
culture: CultureInfo.GetCultureInfo("ar-SA"),
format: "dd/MMMM/yyyy");
// Weird :) I supposed dd/yyyy/MMMM but that did not work !?$^&*
System.Diagnostics.Debug.Assert(
date.Equals(new DateTime(year: 2016, month: 5, day: 18)));
}
}
}
I tried various ways. What worked for me was this:
Convert.ToDateTime(data, CultureInfo.InvariantCulture);
data for me was times like this 9/24/2017 9:31:34 AM
Try the below, where strDate is your date in 'MM/dd/yyyy' format
var date = DateTime.Parse(strDate,new CultureInfo("en-US", true))
Convert.ToDateTime or DateTime.Parse
DateTime.Parse
Syntax:
DateTime.Parse(String value)
DateTime.Parse(String value, IFormatProvider provider)
DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)
Example:
string value = "1 January 2019";
CultureInfo provider = new CultureInfo("en-GB");
DateTime.Parse(value, provider, DateTimeStyles.NoCurrentDateDefault););
Value: string representation of date and time.
Provider: object which provides culture specific info.
Styles: formatting options that customize string parsing for some date and time parsing methods. For instance, AllowWhiteSpaces is a value which helps to ignore all spaces present in string while it parse.
It's also worth remembering DateTime is an object that is stored as number internally in the framework, Format only applies to it when you convert it back to string.
Parsing converting a string to the internal number type.
Formatting converting the internal numeric value to a readable
string.
I recently had an issue where I was trying to convert a DateTime to pass to Linq what I hadn't realised at the time was format is irrelevant when passing DateTime to a Linq Query.
DateTime SearchDate = DateTime.Parse(searchDate);
applicationsUsages = applicationsUsages.Where(x => DbFunctions.TruncateTime(x.dateApplicationSelected) == SearchDate.Date);
Full DateTime Documentation
string input;
DateTime db;
Console.WriteLine("Enter Date in this Format(YYYY-MM-DD): ");
input = Console.ReadLine();
db = Convert.ToDateTime(input);
//////// this methods convert string value to datetime
///////// in order to print date
Console.WriteLine("{0}-{1}-{2}",db.Year,db.Month,db.Day);
You could also use DateTime.TryParseExact() as below if you are unsure of the input value.
DateTime outputDateTimeValue;
if (DateTime.TryParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out outputDateTimeValue))
{
return outputDateTimeValue;
}
else
{
// Handle the fact that parse did not succeed
}
I just found an elegant way:
Convert.ChangeType("2020-12-31", typeof(DateTime));
Convert.ChangeType("2020/12/31", typeof(DateTime));
Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));
Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));
Convert.ChangeType("11/شعبان/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));
Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"
Put this code in a static class> public static class ClassName{ }
public static DateTime ToDateTime(this string datetime, char dateSpliter = '-', char timeSpliter = ':', char millisecondSpliter = ',')
{
try
{
datetime = datetime.Trim();
datetime = datetime.Replace(" ", " ");
string[] body = datetime.Split(' ');
string[] date = body[0].Split(dateSpliter);
int year = date[0].ToInt();
int month = date[1].ToInt();
int day = date[2].ToInt();
int hour = 0, minute = 0, second = 0, millisecond = 0;
if (body.Length == 2)
{
string[] tpart = body[1].Split(millisecondSpliter);
string[] time = tpart[0].Split(timeSpliter);
hour = time[0].ToInt();
minute = time[1].ToInt();
if (time.Length == 3) second = time[2].ToInt();
if (tpart.Length == 2) millisecond = tpart[1].ToInt();
}
return new DateTime(year, month, day, hour, minute, second, millisecond);
}
catch
{
return new DateTime();
}
}
In this way, you can use
string datetime = "2009-05-08 14:40:52,531";
DateTime dt0 = datetime.TToDateTime();
DateTime dt1 = "2009-05-08 14:40:52,531".ToDateTime();
DateTime dt5 = "2009-05-08".ToDateTime();
DateTime dt2 = "2009/05/08 14:40:52".ToDateTime('/');
DateTime dt3 = "2009/05/08 14.40".ToDateTime('/', '.');
DateTime dt4 = "2009-05-08 14:40-531".ToDateTime('-', ':', '-');
String now = DateTime.Now.ToString("YYYY-MM-DD HH:MI:SS");//make it datetime
DateTime.Parse(now);
this one gives you
2019-08-17 11:14:49.000
Different cultures in the world write date strings in different ways. For example, in the US 01/20/2008 is January 20th, 2008. In France this will throw an InvalidFormatException. This is because France reads date-times as Day/Month/Year, and in the US it is Month/Day/Year.
Consequently, a string like 20/01/2008 will parse to January 20th, 2008 in France, and then throw an InvalidFormatException in the US.
To determine your current culture settings, you can use System.Globalization.CultureInfo.CurrentCulture.
string dateTime = "01/08/2008 14:50:50.42";
DateTime dt = Convert.ToDateTime(dateTime);
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}, Hour: {3}, Minute: {4}, Second: {5}, Millisecond: {6}",
dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
This worked for me:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dt = DateTime.ParseExact("2009-05-08 14:40:52,531","yyyy-MM-dd HH:mm:ss,fff", provider);
Do you want it fast?
Let's say you have a date with format yyMMdd.
The fastest way to convert it that I found is:
var d = new DateTime(
(s[0] - '0') * 10 + s[1] - '0' + 2000,
(s[2] - '0') * 10 + s[3] - '0',
(s[4] - '0') * 10 + s[5] - '0')
Just, choose the indexes according to your date format of choice. If you need speed probably you don't mind the 'non-generic' way of the function.
This method takes about 10% of the time required by:
var d = DateTime.ParseExact(s, "yyMMdd", System.Globalization.CultureInfo.InvariantCulture);

Get Indian Time only in HH:MM hours & mins

I am using following code to get local(IST) time. But I don't want to display Date & seconds and also want it in 12hr (AM / PM) format. Please help.
With following code I am getting time like this
9/13/2016 11:38:17 AM
I want it like this
11:38 AM
partial class Default3 : System.Web.UI.Page
{
DateTime UTCTime = System.DateTime.UtcNow;
DateTime IndianTime = UTCTime.AddHours(5.5);
private void Default3_Load(object sender, EventArgs e)
{
myTime.Text = IndianTime;
}
public Default3()
{
Load += Default3_Load;
}
}
You can display your datetime like this
DateTime dt = DateTime.Parse("6/22/2009 07:00:00 AM");
dt.ToString("HH:mm"); // 07:00 // 24 hour clock // hour is always 2 digits
dt.ToString("hh:mm tt"); // 07:00 AM // 12 hour clock // hour is always 2 digits
dt.ToString("H:mm"); // 7:00 // 24 hour clock
dt.ToString("h:mm tt"); // 7:00 AM // 12 hour clock
To get time in India in request format, you can use this
var zone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
var timeInIndia = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, zone);
var timeInIndiaAsString = timeInIndia.ToString("hh:mm tt", CultureInfo.InvariantCulture);
Try:
partial class Default3 : System.Web.UI.Page
{
UTCTime = System.DateTime.UtcNow;
IndianTime = UTCTime.AddHours(5.5).Date;
private void Default3_Load(object sender, EventArgs e)
{
myTime.Text = IndianTime.ToShortDateString();
}
public Default3()
{
Load += Default3_Load;
}
}
If that doesn't work, try something like:
DateTime UTCTime = System.DateTime.UtcNow;
DateTime IndianTime = UTCTime.AddHours(5.5).Date;
partial class Default3 : System.Web.UI.Page
{
private void Default3_Load(object sender, EventArgs e)
{
UTCTime = System.DateTime.UtcNow;
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0);
IndianTime = epoch.AddDays(Math.Floor(IndianTime.Subtract(epoch).TotalDays));
myTime.Text = IndianTime.ToShortDateString();
}
public Default3()
{
Load += Default3_Load;
}
}
The second example is overkill in terms of formatting, but useful if you need to compare a DateTime to something stored as a Date (as in a database). The result of IndianTime in the second example will evaluate to "true" if you need to "remove the time for a DateTime."
Remember - a DateTime is nothing but an integer - it's up to you to format it however you want.

How to get the day value out of a textbox in C#?

For example, if the textbox contains 11/11/2016 OR 01/05/2016
How to get the day value only? example. 11 OR 01
One way is to parse the string in the TextBox to DateTime using an exact format. Then using the DateTime object, you can extract the Day Property:
DateTime date;
bool success = DateTime.TryParseExact(textBoxDate.Text, "dd/MM/yyyy",
CultureInfo.CurrentCulture,
DateTimeStyles.AssumeLocal, out date);
int day;
if(success)
{
day = date.Day; // 1
// or string stringDay = date.ToString("dd"); to get 01
}
else
{
// handle error
}
Another way that I don't prefer (Not 100% safe input validation) is to use String.Split like this:
string strDay = textBoxDate.Text.Split('/').FirstOrDefault();
int day;
if(Int32.TryParse(strDay, out day))
{
// success
}
else
{
// Handle Error
}
string myString = textbox1.text;
DateTime day = DateTime.ParseExact(myString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
int day = birthday.Day;

C# Date formatting issue

I have the following:
string QDI_DATE_FORMAT = "yyyy-MM-ddTHH:mm:00.0000000K";
string from = "2016-06-20T16:20:00.0000000-04:00";
string to = "2016-06-21T16:21:00.0000000-04:00";
DateTime fromDate = DateTime.ParseExact(from, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None).Date;
DateTime toDate = DateTime.ParseExact(to, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None).Date;
Console.WriteLine(fromDate);
Console.WriteLine(toDate);
This prints out the Date without the hour and minutes. How do I make it work and show the time?
By using .Date you are selecting the date part only from the resulted DateTime object. So the default value for the time will be applied, Remove .Date then you will get the expected result;
DateTime fromDate = DateTime.ParseExact(from, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime toDate = DateTime.ParseExact(to, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
This Example will show you the difference
You are calling .date which is selecting just the date part:
string from = "2016-06-20T16:20:00.0000000-04:00";
DateTime fromDateTime = DateTime.ParseExact(from, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime toDateTime = DateTime.ParseExact(to, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
Will produce:
> 6/20/2016 8:20:00 PM
> 6/21/2016 8:21:00 PM
Notice the lack of .Date on the end
What you have to do just remove your ending ".Date" from your code.
string QDI_DATE_FORMAT = "yyyy-MM-ddTHH:mm:00.0000000K";
string from = "2016-06-20T16:20:00.0000000-04:00";
string to = "2016-06-21T16:21:00.0000000-04:00";
DateTime fromDate = DateTime.ParseExact(from, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime toDate = DateTime.ParseExact(to, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
Console.WriteLine(fromDate);
Console.WriteLine(toDate);
Console.ReadLine();

Categories