DateTime.ParseExact() confusing - c#

Why I can apply that code to other form .cs
string dt = day + "/" + month + "/" + year;
DateTime newDate = DateTime.ParseExact(dt, "dd/MM/yyyy", null);
It always show error this
String was not recognized as a valid DateTime.
It have to change like this
"dd/MM/yyyy" --> "d/M/yyyy"
But in other form .cs, that code works. Don't need to change that string

By specifying dd and MM you require the input to be 2 characters wide.Your code will work for 10/10/2015, but not for 1/1/2015.
Change your code to allow single day and month characters and you will be fine:
DateTime newDate = DateTime.ParseExact(dt, "d/M/yyyy", null);

I think your variables day and month does not contain leading 0 and that's why your parsing is not working. Here are some references to the MSDN page were you can find out more about ParseExact and Time formats

if you know date parts, there is a simple way to construct DateTime:
from ints:
int day = 1;
int month = 1;
int year = 2015;
DateTime newDt = new DateTime(year, month, day);
Console.WriteLine(newDt);
from strings:
string sday = "1";
string smonth = "1";
string syear = "2015";
DateTime newDts = new DateTime(int.Parse(syear), int.Parse(smonth), int.Parse(sday));
Console.WriteLine(newDts);
demo

dd/MM/yyyy requires two digits for the day and month, as in 10/09/YYYY; whereas d/M/yyyy accepts one or digits!
Read about the format codes on MSDN.
The code dt = day + "/" + month + "/" + year will not add leading zeroes to day and month.
I suggest using a DateTime constructor, as in
DateTime newDate = DateTime(year, month, day);
Then you will not have any issues with string formats.

Related

Parse a string to datetime format

I have here a little problem and would like to know where is my mistake and how to correct it.
string preConvDATE = monthCombobox2.Text + " " + datecombobox2.Text + ","+ "0000";
//lets say the comboboxes contain something like this "January 1";
DateTime DT = DateTime.ParseExact(preConvDATE, "MMMM d, yyyy 00:00:00", System.Globalization.CultureInfo.InvariantCulture);
string strDate = DT.ToString("yyyy-mm-dd");
try
{
//code that inserts strDate to a column in Mysql DB
}
catch
{
//msg
}
why "0000" for the year? because i was really planning to store just the month and date, but realized i could just store it as a datetime format with a year, and then at viewing the table i'd just use the Mysql MONTH() and DATE() function concatenated to view the Month and Date i stored from the monthCombobox2 and datecombobox2.
I also tried:
Convert.ToDateTime()
But still won't work.
How do i properly parse MMMM d,yyyy date format so that i could convert it to yyyy-mm-dd again and store it as datetime format in the database?
Thank you so much :)
As I can see, you are using text boxes to catch the value of month and date, instead of that you can use dropdowns which will display the month name but return the values like 01 for January and so on. It will be easy for you to format date formats. You don't want to save year that's okay, instead of setting 0000 you can set the current year. Now the problem with that you will not able to figure out the what exactly day was it (e.g Sunday, Monday and so on).
string preConvDATE = monthCombobox2.Text + "/" + datecombobox2.Text+"/" + DateTime.Now.Year.ToString();
DateTime DT = DateTime.ParseExact(preConvDATE, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string strDate = DT.ToString("yyyy-MM-dd");
I hope this will solve your problem. Happy Coding!

I want to covert julian date(YYJJJ format) to any normal date format(MMDDYY) using c#. Is there any defined function for that?

Hi I have julian date string YYJJJ format. eg 05365(31st dec 2005). I want to covert to MMDDYY format(123105).
Is there any defined function for that in?
I faced same problem as I was try to convert dates from BACS 18 standard to a String. I couldn't find ready solution to this problem so I wrote this function:
private String bacsDateConvert(String bacsFormatDate)
{
int dateYear = Convert.ToInt16(bacsFormatDate.Substring(1, 2));
int dateDays = Convert.ToInt16(bacsFormatDate.Substring(3, 3));
DateTime outputDate = new DateTime();
outputDate = Convert.ToDateTime("31-12-1999");
outputDate = outputDate.AddYears(dateYear);
outputDate = outputDate.AddDays(dateDays);
String outputString = outputDate.ToString("yyyyMMdd");
return outputString;
}
//You may call it like this:
textBox4.Text = Convert.ToString(bacsDateConvert(bacsTxnValueDate));
You also may modify it slightly and easily make it return DateTime data type if you want to. I just needed to return a string in the above format.
First of all, there is no YY, JJJ and DD formats as a custom date and time format. One solution might be to split your string Year and DayOfYear part and create a DateTime with JulianCalendar class.
string s = "05365";
int year = Convert.ToInt32(s.Substring(0, 2));
// Get year part from your string
int dayofyear = Convert.ToInt32(s.Substring(2));
// Get day of years part from your string
DateTime dt = new DateTime(1999 + year, 12, 18, new JulianCalendar());
// Initialize a new DateTime one day before year value.
// Added 1999 to year part because it makes 5 AD as a year if we don't.
// In our case, it is 2004/12/31
dt = dt.AddDays(dayofyear);
// Since we have a last day of one year before, we can add dayofyear to get exact date
I initialized this new DateTime(.. part with 18th December because
From Julian Calendar
Consequently, the Julian calendar is currently 13 days behind the
Gregorian calendar; for instance, 1 January in the Julian calendar is
14 January in the Gregorian.
And you can format your dt like;
dt.ToString("MMddyy", CultureInfo.InvariantCulture) //123105
I honestly didn't like this way but this is the only one I can imagine as a solution.

C# DateTime.ParseExact determining year prefix

I have a requirement regarding the parsing of date strings of the form "dd/MM/yy" such that if the year is deemed greater than 30 years from the current year then it would prefix the year with 19. In the other instance it is prefixed with 20.
Examples:
01/01/50 -> 01/01/1950
01/01/41 -> 01/01/2041
I'm not sure how DateTime.ParseExact decides what prefix it should use or how I can force it one way or the other (it does appear to make a sane assumption as 01/01/12 -> 01/01/2012, I just don't know how to dictate the point at which it will switch).
Use the Calendar.TwoDigitYearMax property.
Gets or sets the last year of a 100-year range that can be represented
by a 2-digit year.
In your case, something like this would work:
// Setup
var cultureInfo = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
var calendar = cultureInfo.Calendar;
calendar.TwoDigitYearMax = DateTime.Now.Year + 30;
cultureInfo.DateTimeFormat.Calendar = calendar;
// Parse
var _1950 = DateTime.ParseExact("01/01/50", "dd/MM/yy", cultureInfo);
var _2041 = DateTime.ParseExact("01/01/41", "dd/MM/yy", cultureInfo);
I do not think that ParseExact can do your job, so here my version with conditional blocks but works.
Try This:
DateTime currentDate = DateTime.Now;
String strDate = "01/01/41";
DateTime userDate=DateTime.ParseExact(strDate, "dd/MM/yy", System.Globalization.CultureInfo.InvariantCulture);
currentDate=currentDate.AddYears(30);
if ((userDate.Year%100) > (currentDate.Year%100))
{
strDate = strDate.Insert(6, "19");
}
else
{
strDate = strDate.Insert(6, "20");
}
DateTime newUserDate = DateTime.ParseExact(strDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);

Join date and time strings into a DateTime

Given two strings with the following values:
31/05/2013 0:00:00
21:22
What's the most efficient way to join them into a DateTime data type to get:
31/05/2013 21:22
The time portion of the first string "0:00:00" is ignored, in favor of using the "time" from the second string.
Use a TimeSpan object and DateTime.Add(yourTimeSpan); e.g.
DateTime dt = new DateTime(2013,05,31);
var dts = dt.Add(new TimeSpan(0, 21, 22, 0, 0));
Extending the answer a bit, you can parse the date and time first, e.g.
DateTime dt = DateTime.Parse("05/31/2013 0:00:00");
TimeSpan ts = TimeSpan.Parse("21:22");
var dts = dt.Add(ts);
...keep in mind, I am not checking for bad date/time values. If you're unsure if the values are real dates/times, use DateTime.TryParse and handle appropriately.
As #George said, parse the first value as a DateTime and then another one as TimeSpan and then add the TimeSpan to first parsed value.
Another option is getting the substring of first 10 charachters of first value and concat it with a space with second value and parse it as DateTime.
Say that the first string is called one and the second one is called two, just do this:
DateTime result = DateTime.Parse(one).Date + DateTime.Parse(two).TimeOfDay;
string strDate = "31/05/2013 0:00";
string strTime = "21:22";
strDate = strDate.Replace("0:00", strTime);
DateTime date = Convert.ToDateTime(strDate);
If you are really dealing with only strings, then:
string strDate = "31/05/2013 0:00:00";
string strTime = "21:22";
string strDateTime = strDate.Split(' ')[0] + " " + strTime;
If you can safely assume you are getting 2 digit month and day, a 4 digit year, and a space after the date:
var date = "31/05/2013 0:00:00";
var time = "21:22";
var dateTime = DateTime.Parse(date.Substring(0,11) + time);
If the assumptions about the input format aren't solid you could use a regex to extract the date instead of Substring.
If you're starting out with just strings, you can just do this:
var dateString = "31/05/2013 00:00";
var timeString = "21:22";
var dateTimeString = dateString.Substring(0, 11) + timeString;
var output = DateTime.ParseExact(dateTimeString, "dd/MM/yyyy HH:mm", null);
Assuming you know for sure this format won't change (a dangerous assumption, to be sure), this will work. Otherwise, you'd have to parse the date and time strings separately and use conventional date manipulation as others suggested. For example:
var ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
var dateString = "31/05/2013 00:00";
var timeString = "21:22";
var output = DateTime.Parse(dateString, ci) + TimeSpan.Parse(timeString, ci);
DateTime date = DateTime.ParseExact("31/05/2013 0:00:00", "dd/MM/yyyy h:mm:ss", CultureInfo.InvariantCulture);
TimeSpan span = TimeSpan.ParseExact("21:22", "t", CultureInfo.InvariantCulture);
DateTime result = date + span;

How to combine two strings (date and time) to a single DateTime

I have two strings:
string one = "13/02/09";
string two = "2:35:10 PM";
I want to combine these two together and convert to a DateTime.
I tried the following but it doesn't work:
DateTime dt = Convert.ToDateTime(one + " " + two);
DateTime dt1 = DateTime.ParseExact(one + " " + two, "dd/MM/yy HH:mm:ss tt", CultureInfo.InvariantCulture);
What can I do to make this work?
Try like this;
string one = "13/02/09";
string two = "2:35:10 PM";
DateTime dt = Convert.ToDateTime(one + " " + two);
DateTime dt1 = DateTime.ParseExact(one + " " + two, "dd/MM/yy h:mm:ss tt", CultureInfo.InvariantCulture);
Console.WriteLine(dt1);
Here is a DEMO.
HH using a 24-hour clock from 00 to 23. For example; 1:45:30 AM -> 01 and 1:45:30 PM -> 13
h using a 12-hour clock from 1 to 12. For example; 1:45:30 AM -> 1 and 1:45:30 PM -> 1
Check out for more information Custom Date and Time Format Strings
Your issue is with your hour specifier; you want h (The hour, using a 12-hour clock from 1 to 12), not HH (The hour, using a 24-hour clock from 00 to 23).
I had different format and the above answer did not work:
string one = "2019-02-06";
string two = "18:30";
The solution for this format is:
DateTime newDateTime = Convert.ToDateTime(one).Add(TimeSpan.Parse(two));
The result will be: newDateTime{06-02-2019 18:30:00}
Try using a culture info which matches the DateTime format for your string values:
DateTime dt = Convert.ToDateTime(one + " " + two,
CultureInfo.GetCultureInfo("ro-RO"));
or modify the input string so that the hour has 2 digits:
string one = "13/02/09";
string two = "02:35:10 PM";
DateTime dt1 = DateTime.ParseExact(one + " " + two,
"dd/MM/yy HH:mm:ss tt",
CultureInfo.InvariantCulture);
The problem is that the format string that you specify is not correct.
'HH' means a dwo-digit hour, but you have a single digit hour.
Use 'h' instead.
So the full format is 'dd/MM/yy h:mm:ss tt'
The following code will do what you want. I used the UK culture to take care of the d/m/y structure of your date:
string string1 = "13/2/09";
string string2 = "2:35:10 PM";
DateTime combined = DateTime.Parse(string1 + ' ' + string2, new CultureInfo("UK"));
Use string two = "02:35:10 PM"; instead of string two = "2:35:10 PM"; and also hh instead of HH due to AM/PM format.
Below is the code:
string one = "13/02/09";
string two = "02:35:10 PM";
DateTime dateTime = DateTime.ParseExact(one + " " + two, "dd/MM/yy hh:mm:ss tt", CultureInfo.InvariantCulture);
Convert.ToDateTime uses DateTime.ParseExact with your current thread's culture, so you can make things a bit clearer by simply doing:
string date = "13/02/09";
string time = "2:35:10 PM";
DateTime dateTime = DateTime.Parse(date +" "+ time, new CultureInfo("en-GB"));
Console.WriteLine (dateTime);
That gives the result 13/02/2009 14:35:10, and forces the parse to use the en-GB date time formats. If your Windows installation is en-GB anyway, you don't need the CultureInfo(..) argument.
use DateTime.Parse () to parse the date and the time separately. Then add the time component of the second one to the first one, like this
var date = DateTime.Parse (one);
var time = DateTime.Parse (two);
var result = date + time - time.Date;

Categories