C# custom time format - c#

Subtraction two time format ,
string _time_One = "08:30" ;
string _time_Two = "08:35" ;
string _timeInterval = ( DateTime.Parse(_time_One) - DateTime.Parse(_time_Two) ).Minutes.ToString();
It give me the result 5 , but I want to show likes this format 00:05.
Kindly show me how to format it . Thanks in advance !

Subtracting two DateTime gives you a TimeSpan which has it's own formatting support using the ToString method.
For example:
DateTime now = DateTime.Now;
DateTime later = now.AddMinutes(10);
TimeSpan span = later - now;
string result = span.ToString(#"hh\:mm");
You can read more here on MSDN.

Try this:
string _time_One = "08:30";
string _time_Two = "08:35";
var span = (DateTime.Parse(_time_One) - DateTime.Parse(_time_Two));
string _timeInterval = string.Format("{0:hh\\:mm}", span);
For reference: Custom TimeSpan Format Strings.

#Lloyd is right here, but to clarify this for your case:
string _time_One = "08:30" ;
string _time_Two = "08:35" ;
TimeSpan ts = DateTime.Parse(_time_One) - DateTime.Parse(_time_Two);
MessageBox.Show(String.Format("Time: {0:00}:{1:00}", ts.Hours, ts.Minutes));
I hope this helps.

string _time_One = "08:30";
string _time_Two = "08:35";
string _timeInterval = (DateTime.Parse(_time_One) - DateTime.Parse(_time_Two)).Duration().ToString();
result=>00:05:00

Related

Csharp Swapping Dynamic values in string

I want to swap two values in a STRING
This is an example of doing it with characters:
string str = "PQRQP";
var res= str.Select(a=> a == 'P' ? 'Q' : (a=='Q' ? 'P' : a)).ToArray();
str = new String(res);
Console.WriteLine(str);
But my string is 2/7/2019, where i want to swap the 2 and 7 each time but as these values are from user input i wont know what they will be before runtime.
Any help appreciated, thanks in advance !
-----------MY SOLUTION----------------
String values = DateRangePicker1.Value.ToString();
String startDate = values.Substring(0, 8);
String endDate = values.Substring(11, 8);
DateTime date = DateTime.ParseExact(startDate, "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime date1 = DateTime.ParseExact(endDate, "M/d/yyyy", CultureInfo.InvariantCulture);
String newSDate = date.ToString();
String newEDate = date1.ToString();
String finalSDate = newSDate.Substring(0, 10);
String finalEDate = newEDate.Substring(0, 10);
I know this is slightly messy, but is working for me without affecting performance
This rather seems to be a localization issue (based on the fact that you are providing a string that looks like a date)
Is it possible that by just providing the correct date annotation that this would solve your problem?
DateTime.ParseExact(string)
for instance is a method that allows you to create a datetime object from a string, if you tell it what the string format is
example:
DateTime date = DateTime.ParseExact("2/1/2019", "M/d/yyyy", CultureInfo.InvariantCulture);
will provide a datetime object set to the first of febuary 2019. You can then convert the datetime object to a string with:
date.ToString("dd-MM-yy");
output: 01-02-19
Edit: if you have a range of acceptable formats, it is possible to provide an array of formats in string form.
You can use split to get the charachters you dont know.
Like this:
var sepratedInput = input.split('/');
var res= sepratedInput[1] +"/"+sepratedInput[0]+"/"+sepratedInput[2];
Console.write(res);

Remove '0' (Number) from DateTime Month and Day (String)

Can anybody tell me the best approach or solution on how I would do the following?
I have a DateTime (as String) in following format:
string test = "21.12.2013";
How could I now remove all zero's from the month and day but still 'keep' the DateTime Logic:
//Example 1
string input = "06.10.2013" // 6th October
string output = "6.10.2013" //only remove '0' from the day
//Example 2
string input = "01.09.2012" // 1st September
string output = "1.9.2012" //remove from month and day
//Example 3
string input = "20.10.2011" // 20th October
string output = "20.10.2011" //should (must) stay!
I can also parse to DateTime if that would be make it easier but yeah I hope you got my idea...
Any help appreciated!
Parsing your string into DateTime and getting it back to string using ToString with desired patter seems to be the easiest way to go:
public static string GetRidOfZeros(string input)
{
var dt = DateTime.ParseExact(input, "dd.MM.yyyy", CultureInfo.InvariantCulture);
return dt.ToString("d.M.yyyy", CultureInfo.InvariantCulture);
}
Little testing, with your sample data:
var inputs = new List<string> { "06.10.2013", "01.09.2012", "20.10.2011" };
var outputs = new List<string> { "6.10.2013", "1.9.2012","20.10.2011" };
if(outputs.SequenceEqual(inputs.Select(d => GetRidOfZeros(d))))
Console.WriteLine("Output is OK");
else
Console.WriteLine("Collections does not match.");
Prints Output is OK.
DateTime.Parse(input).ToString("d.M.yyyy")
As you said, parsing to DateTime first would probably make things easier, since then you can just use:
myDateTime.ToString("d.M.yyyy");
When you parse it you can use ToString to format it any way you like:
var date = "06.10.2013";
DateTime parsed = DateTime.ParseExact(date, "dd.MM.yyyy", CultureInfo.InvariantCulture);
var noZerosHere = parsed.ToString("d.MM.yyyy");
A decent "catch-all" method (that will work not just on DateTime but ANY kind of string) would be to split the string up, take out leading zeroes and then put the pieces back together again.
string input = "01.09.2012";
string[] values = input.Split(".");
string[] modifiedValues = values.Select(x => x.TrimStart('0');
string output = String.Join(".", modifiedValues);
You can adjust the delimiters for different representations of DateTime, e.g. those that use slashes (01/09/2012) or are written in a different order.

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;

Split String at position in C#

I have a date stamp (020920111422) and I want to split it to
day = 02,
month = 09,
year = 2011,
hour = 14,
and minute = 22
Is there a "split string at position" method in C#?
You want:
string x = s.Substring(0, i), y = s.Substring(i);
(or maybe i-1/i+1 depending on your exact requirements).
However, you could also use DateTime.ParseExact to load it into a DateTime by telling it the explicit format:
var when = DateTime.ParseExact("020920111422", "ddMMyyyyHHmm",
CultureInfo.InvariantCulture);
you can do this via SubString - for example:
string myDay = mydatestamp.SubString (0,2);
OR create a DateTime:
DateTime myDateTime = DateTime.ParseExact ( mydatestamp, "ddMMyyyyHHmm" , CultureInfo.InvariantCulture );
Answering on question considering "split string at position" - you can leverage String.Substring(Int32, Int32) method by calling multiple times with different offsets.
Also take a look at LINQ Take() and Skip() methods which allows provide count of elements to return as well.
Otherwise see examples which other guys are provided using DateTime.ParseExact(), I believe this is most correct way to convert string you've provided to DateTime value.
You could also use
var d = DateTime.Parse(s, "ddMMyyyyHHmm");
if the end-goal is a DateTime.
Instead you can convert the date stamp by using Datatime.ParseExact and can extract the day, month, year, hour and minute you want from that date stamp. Refer the following code part for Datetime.ParseExact converting.
DateTime.ParseExact(YourDate, "ddMMyyyyHHmm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)
For more usecase, maybe this can help
string rawData = "LOAD:DETAIL 11.00.0023.02.201614:52:00NGD ...";
var idx = 0;
Func<int, string> read = count =>
{
var result = rawData.Substring(idx, count);//.Trim();
idx += count;
return result;
};
var type = read(16);
var version = read(8);
var date = read(18);
var site = read(8);
//...

Hour from DateTime? in 24 hours format

So i have this DateTime? and what i want to do is to obtain the hour but show it in 24 hours format.
For example:
If the hour is 2:20:23 p.m. i want to convert it to 14:20 and that's it.
I'm working with Visual C#.
Any ideas please, thank you.
I have something like this
public static string FormatearHoraA24(DateTime? fechaHora)
{
if (!fechaHora.HasValue)
return "";
string retornar = "";
//here goes what i need
}
You can get the desired result with the code below. Two 'H' in HH is for 24-hour format.
return fechaHora.Value.ToString("HH:mm");
date.ToString("HH:mm:ss"); // for 24hr format
date.ToString("hh:mm:ss"); // for 12hr format, it shows AM/PM
Refer this link for other Formatters in DateTime.
Using ToString("HH:mm") certainly gives you what you want as a string.
If you want the current hour/minute as numbers, string manipulation isn't necessary; you can use the TimeOfDay property:
TimeSpan timeOfDay = fechaHora.TimeOfDay;
int hour = timeOfDay.Hours;
int minute = timeOfDay.Minutes;
Try this:
//String.Format("{0:HH:mm}", dt); // where dt is a DateTime variable
public static string FormatearHoraA24(DateTime? fechaHora)
{
if (!fechaHora.HasValue)
return "";
return retornar = String.Format("{0:HH:mm}", (DateTime)fechaHora);
}
Try this, if your input is string
For example
string input= "13:01";
string[] arry = input.Split(':');
string timeinput = arry[0] + arry[1];
private string Convert24To12HourInEnglish(string timeinput)
{
DateTime startTime = new DateTime(2018, 1, 1, int.Parse(timeinput.Substring(0, 2)),
int.Parse(timeinput.Substring(2, 2)), 0);
return startTime.ToString("hh:mm tt");
}
out put: 01:01
Another method
var time = DateTime.Now;
string foo = $"{time:HH:mm}";
Where I find this useful is if there is more than just the time in the string.
string bar = $"The time is {time:HH:mm}";

Categories