c# exception when parsing a string to datetime - c#

I have a date time variable DateTime d which has data.
I have string like this:
11:00 - 12:00
I want to take the date from the d variable then add the hour and minute from the string.
I did this:
string newStringDate = d.ToString("yyyy-mm-dd") + " "+hourValue.Split('-')[0];
DateTime dd = DateTime.Parse(newStringDate);
I got excpetion that the string can't be transfered to date.
I debug the code and I can see that the newStrinDate = 2014-01-25 11:00
what am i doing wrong please?

It should be like this
string newStringDate = d.ToString(#"yyyy\-MM\-dd") + " " + hourValue.Split('-')[0].Trim();
DateTime dd = DateTime.ParseExact(newStringDate, #"yyyy\-MM\-dd HH\:mm", null);
You can do even better (no need to convert original date to string):
DateTime dd = d.Date + DateTime.ParseExact(hourValue.Split('-')[0].Trim(), #"HH\:mm", null).TimeOfDay;

Related

Convert.DateTime throws error: String was not recognized as a valid DateTime for "JAN 1996"

I am displaying a date into a pdf form , the value which comes from:
s.getString(UserName, "FromMonth", "id123") + " " + s.getString(UserName, "FromYear", "id123");
Which results to this :
JAN 1996
I tried this code:
String month;
DateTime myDateTime;
myDateTime = DateTime.Parse(s.GetString(UserName, "FromMonth", "id123") + " " + s.GetString(UserName, "FromYear", "id123"));
month = myDateTime.ToShortDateString();
pdfFormFields("sample",month);
But it gives me an error(refer to the title)
pdfFormFields.SetField("sample", DateTime.ParseExact(s.GetString(UserName, "FromMonth", "id123") + " " + s.GetString(UserName, "FromYear", "id123"), "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString());
But it also gives me an error , any tips to fix this?
I tried the first code before in some parts of my code and it works , it only in this part the gives me an error.
BDW , I want the result to be like thus "01/01/1996" , which makes the DAY default into 01
"MM/dd/yyyy" won't work because you have no day specified in "JAN 1996" and the format looks totally different.
Use "MMM yyyy" instead. MMM for abbreviated name of the month.
string input = "JAN 1996";
string pattern = "MMM yyyy";
DateTime result = DateTime.ParseExact(input, pattern, System.Globalization.CultureInfo.InvariantCulture);

Convert from DateTime to TimeStamp

I am trying to convert a DateTime variable to Timestamp. My variable has the current format : 1/23/17 2:14:31 PM and I would like it to be TimeStamp like so I can use it for Oracle SQL Developer. eg: 23-JAN-17 2.14.31.000000000 PM.
I have tried to convert it like this:
DateTime d = DateTime.Now.AddDays(-31);
Console.WriteLine(d.ToUniversalTime().ToString("O"));
but the output is nothing like TimeStamp:
2017-01-23T14:14:31.5838355Z
Try this:
DateTime d = DateTime.Now.AddDays(-31);
long epoch = (d.Ticks - 621355968000000000) / 10000000;
Console.WriteLine(d.ToUniversalTime().ToString("dd-MMM-yy HH:mm:ss") + ":" + epoch);
Try this one
DateTime d = DateTime.Now.AddDays(-31);
Console.WriteLine(d.ToUniversalTime().ToString("hh-MMM-yy hh.mm.ss.ffffff tt"));

DateTime.ParseExact() confusing

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.

Join date and time in c#

I have a win form c# SQL app that stores date in one column and time in the another.
There is only one date time picker on my form and I want to display both date and time values (which are from two separate columns)..
So far this is what I've done
Datetime final = datetime. Parse exact (date + " " + time , "MM/dd/yyyy hh:mm tt", cultureinfo. Invariant culture);
But it throws " string was not recognized as valid datetime" exception on the above line.
If date and time are DateTime variables, you can combine them with date arithmetic:
DateTime date=...;
DateTime time = ...;
DateTime finalDate = date.Date + time.TimeOfDay;
If they are strings, you can parse them to DateTime and TimeSpan variables:
DateTime date=DateTime.ParseExact(dateString,dateFormat,CultureInfo.InvariantCulture);
TimeSpan time = TimeSpan.ParseExact(timeString,timeFormat,CultureInfo.InvariantCulture);
DateTime finalDate = date.Date + time;
This is possible because you can add a DateTime and a TimeSpan value to get a new DateTime value
You can use TimeSpan.Parse to parse
DateTime newDateTime = date.Add(TimeSpan.Parse(time));
string d = DateTime.Now.Date.ToString("dd/MM/yyyy");
string t = DateTime.Now.ToString("h:mm");
var ts = TimeSpan.ParseExact(t, #"h\:mm",CultureInfo.InvariantCulture);
DateTime result = DateTime.ParseExact(d, "dd/MM/yyyy", CultureInfo.InvariantCulture)+ts;
Hope this helps,
Thanks.

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