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

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;

Related

Split string on basis of "/"

I have a string:
string s = "1/09/2017 12:00:00 AM";
Output I want to show is 1/09/17 (basically short date).
And if
string s ="30/09/2017 12:00:00 AM"
Output I want to show is 30/09/17 (basically short date).
What I have tried is:
string[] values = s.Split('/');
string a = values[0]+"/"+values[1]+"/"+values[2].
I am confused how to get the 3rd part need help.
Use .NET built-in DateTime parsing.
For example:
string s = "1/09/2017 12:00:00 AM";
string format = "d/MM/yyyy hh:mm:ss tt";
DateTime parsedDateTime = DateTime.ParseExact(s, format, null);
string output = parsedDateTime.ToString("d/MM/yy"); //output = 1/09/17
More info:
DateTime.ParseExact method
DateTime.ToString method
My suggestion would be to use the inbuilt date datatype.
If that doesn't go with your requirement then I would suggest you to split the string based on the delimiter " "(blank space). Then pick the first part and proceed with your code.
You could use a substring like this
string s = "30/09/2017 12:00:00 AM";
string[] values = s.Split('/');
string a = values[0] + "/" + values[1] + "/" + values[2].Substring(2,2);
Adding to Paolo's anwer
string s = "1/09/2017 12:00:00 AM";
string format = "d/MM/yyyy hh:mm:ss tt";
DateTime parsedDateTime = DateTime.ParseExact(s, format, null);
string output = parsedDateTime.ToString("d/MM/yy");
string ss = output.Replace("-","/");
Console.Write(ss); //output is 1/09/17
This will exactly return the exact expected output
DateTime date = DateTime.ParseExact("1/09/2017 12:00:00 AM", "d/MM/yyyy hh:mm:ss tt", null);
Console.WriteLine(date.ToString("d/MM/yy"));
Convert your date string to DateTime and then use ToString overloaded method method with parameter Format Please find Fiddle

Error parsing Datetime format

I am trying to parse two string values into DateTime.
DateTime processStartTime = DateTime.ParseExact(currentDateTime.Date.ToString("dd-MM-yyyy") + " " + "00:00", "dd-MM-yyyy hh:mm", System.Threading.Thread.CurrentThread.CurrentCulture);
DateTime processEndTime = DateTime.ParseExact(currentDateTime.Date.ToString("dd-MM-yyyy") + " " + "13:00", "dd-MM-yyyy hh:mm", System.Threading.Thread.CurrentThread.CurrentCulture);
The first statement works fine, but the second statement fails with exception-
String was not recognized as a valid DateTime
What I am doing wrong?
You have to use HH:mm instead of hh:mm for 24h format
The "hh" custom format specifier:
represents the hour as a number from 01 through 12; that is, the hour
is represented by a 12-hour clock that counts the whole hours since
midnight or noon.
The "HH" custom format specifier:
The "HH" custom format specifier (plus any number of additional "H"
specifiers) represents the hour as a number from 00 through 23; that
is, the hour is represented by a zero-based 24-hour clock that counts
the hours since midnight. A single-digit hour is formatted with a
leading zero.
Are you really converting a DateTime object to a string and then convert it back to a DateTime? Otherwise you could just write:
var startTime = currentDateTime.Date;
var endTime = currentDateTime.Date.AddHours(13);

c# exception when parsing a string to datetime

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;

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;

Parse C# string to hh:mm:ss

Given two strings
string date = "02Mar13";
string duration = "03.20min";
How do I parse them to DateTime and show them in the following format
string date = "02 March 2013";
string duration = "00:03:20";
I went through the list here but no one match my requirements.
You need to parse these using a Custom Date and Time format string, and output using one as well:
DateTime dt = DateTime.ParseExact(date + duration,
"ddMMMyymm.ss'min'",
CultureInfo.InvariantCulture);
string newDate = dt.ToString("dd MMMM yyyy");
string newDuration = dt.ToString("HH:mm:ss");
Things to note: I am using 'min' to represent the min literal in the string - this is part of custom format strings, allowing inner string literals.
string date = "02Mar13";
string duration = "03.20min";
DateTime newDate = DateTime.ParseExact(date + duration, "ddMMMyymm.ss\\min", null);
date = newDate.ToString("dd MMMM yyyy");
duration = newDate.ToString("hh:mm:ss");
How can produce the dateResult
string date = "02Mar13";
string duration = "03.20min";
var mat=Regex.Match(duration, "(.+?)min");
var dateResult = DateTime.ParseExact(date + mat.Groups[1].Value.Replace(".",":"), "ddMMMyyHH:mm", Thread.CurrentThread.CurrentCulture);
DateTime parsing is pretty much straightforward using DateTime.ParseExact:
DateTime.ParseExact(date, "ddMMMyy", null).ToString("dd MMMM yyyy"); // "02 March 2013"
As for the second part, if it is a duration semantically, then it is more suitable to use TimeSpan.ParseExact (although it required some fiddling with format strings):
TimeSpan.ParseExact(duration, "mm\\.ss'min'", null).ToString("hh\\:mm\\:ss"); // "00:03:20"

Categories