Parse C# string to hh:mm:ss - c#

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"

Related

Converting a String to DateTime with new format

How do you convert a string such as 13.11.2017 into a DateTime with that format 13/11/2017
I tried several ways but i didn't get solution .
string Arrival = Request.QueryString["Arrival"];//13.11.2017
DateTime datee = DateTime.ParseExact(Arrival , "dd/MM/yyyy", null);
here is updated code i split the string :
string Arrival = Request.QueryString["Arrival"];//13.11.2017
string year = Arrival.Split('.')[2];
string month = Arrival.Split('.')[1];
string day = Arrival.Split('.')[0];
string date = day + "/" + month + "/" + year;
DateTime datee = DateTime.ParseExact(date, "dd/MM/yyyy", null);
Observe:
// the input string
string inputString = "13.11.2017";
// parse the input string with a specific format to create a DateTime
DateTime dt = DateTime.ParseExact(inputString, "dd.MM.yyyy", CultureInfo.InvariantCulture);
// create a string from the DateTime using a different specific format
string outputString = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
// output the string
Console.WriteLine(outputString); // "13/11/2017"
Note that a DateTime itself does not have any particular format. A format only comes into play when going to or from a string.
Also note that by using the invariant culture here, we are avoiding any issues that may arise if the current culture was one that used different date separators or a different calendar system.
using System.Text.RegularExpressions;
string Arrival = Request.QueryString["Arrival"]; // 13.11.2017
string dateString = Regex.Replace(Arrival, #"\.", "/"); // 13/11/2017
DateTime date = DateTime.ParseExact(dateString , "dd/MM/yyyy", null); // 11/13/2017 00:00:00
Had the same problem with Russian locale.
Currently using ISO format everywhere to avoid incorrect DateTime understandings (like MM.dd when you mean dd.MM).
public static string ToIsoStr(this DateTime dateTime)
{
return dateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
Your task will be solved with
return dateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

DateTime string format in c#

I have a project that contain 3 string variables.
DateFormatStr is the format string I need to use to output dates.
DateFormatFrom is the start date a request will apply from
FilloutDateTo is the end date the request will apply to.
The problem is that I don't want to manually specify the dates. As you can see in my example below (a working example), I need to specify the dates, but is there a way to make it that the from date has time 00:00:00 and the end date has time 23:59:59?
string DateFormatStr = "MM/dd/yy hh:mm:ss tt";
string DateFormatFrom = "12/04/14 00:00:00";
string FilloutDateTo = "12/04/14 23:59:59";
So I would like to the system time to recognize the from date and the start date respecting the formatStr variable.
Thanks
If I understand correctly, you can use DateTime.Today property like;
var dt1 = DateTime.Today;
var dt2 = DateTime.Today.AddDays(1).AddSeconds(-1);
and use DateTime.ToString() to format them like;
var DateFormatFrom = dt1.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
var FilloutDateTo = dt2.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Results will be;
12/04/2014 00:00:00
12/04/2014 23:59:59
You used hh format specifier but it is for 12-hour clock. Use HH format specifier instead which is for 24-hour clock. And since your result strings doesn't have any AM/PM designator, you don't need to use tt format specifier.
In C# 6.0 you can use string interpolation in order to display formatted dates.
DateTime startOfDay = DateTime.Today;
DateTime endOfDay = DateTime.Today.AddDays(1).AddTicks(-1);
string dateFormatFrom = $"{startOfDay: MM/dd/yy hh:mm:ss tt}";
string filloutDateTo = $"{endOfDay: MM/dd/yy hh:mm:ss tt}";
string idate = "01/11/2019 19:00:00";
DateTime odate = Convert.ToDateTime(idate);
DateTime sdate1 = DateTime.Parse(idate);
string outDate1 = String.Format("{0}/{1}/{2}", sdate1.Day, sdate1.Month,sdate1.Year);
Console.WriteLine(outDate1);

Adding two dates to eachother

string final = Convert.ToString(DateTime.Parse(date, System.Globalization.CultureInfo.InvariantCulture) + TimeSpan.Parse(duration));
Hi, I use the above code to add two date's to eachother. It do work very well on Windows and returns the required format yyyy-MM-dd HH:mm:ss in a correct fashion. HOWEVER, when on Linux building with Mono it returns the following format dd/MM/yyyy HH:mm:ss which is not what I want.
How can I specify that I ONLY want the first formatting and nothing else? I tried playing around with ParseExact but it did not do very well. What I've heard ParseExact should not really be needed for this?
Here is a example of input:
string date = "2014-10-30 10:00:04"; // On windows
string duration = "05:02:10"; // duration to be added to date
Greetings.
Use ToString("yyyy-MM-dd HH:mm:ss") instead of Convert.ToString.
string date = "2014-10-30 10:00:04";
string duration = "05:02:10";
DateTime dt1 = DateTime.Parse(date, CultureInfo.InvariantCulture);
TimeSpan ts = TimeSpan.Parse(duration, CultureInfo.InvariantCulture);
DateTime dtFinal = dt1.Add(ts);
string final = dtFinal.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
Convert.ToString uses your current culture's date separator, use CultureInfo.InvariantCulture.
Read: Custom Date and Time Format Strings
You can use the ToString() Method of the DateTime object.
var dt = DateTime.Now;
dt.ToString("yyyy-MM-dd HH:mm");
Using your code:
string _final = (DateTime.Parse(date, System.Globalization.CultureInfo.InvariantCulture) + TimeSpan.Parse(duration)).ToString("yyyy-MM-dd HH:mm:ss");

Reading date from string format

I have to read a date in this format in c#
yyyy/MM/dd HH:mm:ss
I cannot change the format because is written by another application
The date is a string like
2009/11/17 12.31.35
How i can read this format without parsing it(without split if possible)
thanks
I cannot change the format because is written by another application
Solution 1: You don't need to change the format for reading it.
Try This:
DateTime dt;
DateTime.TryParseExact(date, "yyyy/MM/dd HH.mm.ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
OR
How i can read this format without parsing it(without split if
possible)
Solution 2: If you want to extract the values from the date string.
Try This:
string str = "2009/11/17 12.31.35";
string year = str.Substring(0, 4); //2009
string month = str.Substring(5, 2); //11
string date = str.Substring(8, 2); //17
string Hours = str.Substring(11, 2); //12
string minutes = str.Substring(14, 2);//31
string seconds = str.Substring(17, 2);//35
Use DateTime.ParseExact, where you can supply your custom date format
Try replacing . with : an then ParseExtract
string dt= "2009/11/17 12.31.35";
var dt2= ss.Replace('.', ':');
DateTime d = DateTime.ParseExact(dt2, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);
or just
DateTime d = DateTime.ParseExact("2009/11/17 12.31.35", "yyyy/MM/dd HH.mm.ss", CultureInfo.InvariantCulture);

CONVERT MM/DD/YYYY HH:MI:SS AM/PM to DD/MM/YYYY in C#

How can I convert MM/DD/YYYY HH:MI:SS AM/PM into DD/MM/YYYY using C# ?I am using C#2008.
Thanks
Use TryParseExact to parse to a DateTime, then ToString with a format string to convert back...
DateTime dt;
if (DateTime.TryParseExact(value, "MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture, DateTimeStyles.None,
out dt))
{
string text = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
// Use text
}
else
{
// Handle failure
}
As the time part is irrelevant, you can truncate that before parsing and re-formatting:
date = DateTime.ParseExact(date.Substring(0, 10), "MM'/'dd'/'yyyy", CultureInfo.InvariantCulture).ToString("dd'/'MM'/'yyyy");
Edit:
As your comment reveals that you don't want a string as result, you should not format the date into a string, just get the date as a DateTime value:
Datetime dbDate = DateTime.ParseExact(date.Substring(0, 10), "MM'/'dd'/'yyyy", CultureInfo.InvariantCulture);
Now you can use the DateTime value in your code, wrapping it in a database driver type if needed.
If this is a DateTime object, you should be able to just select a different format.
If it is a string, use the following:
public string convert(string date){
string[] pieces = date.Split("/");
string day = pieces[1];
string month = pieces[0];
string year = pieces[2].split(" ")[0];
return day + "/" + month + "/" + year;
}

Categories