How do I convert a string of numbers to 24 time - c#

How do I convert a string of numbers to 24 time
string example would be something like "0800" or "1200" or "2400"
I'd like this to be parsed to time data type (but without date) so that I can compare 2 times against each other. I parsed them as int numbers, but then it trimmed left zero's on numbers like "0800"

var ts = TimeSpan.ParseExact("1500", "hhmm",null);
You can compare them, for ex
var ts1 = TimeSpan.ParseExact("1500", "hhmm", null);
var ts2 = TimeSpan.ParseExact("2000", "hhmm", null);
var mins = ts2.Subtract(ts1).TotalMinutes;

If you want the result as DateTime object, take a look at the DateTime.ParseExact method:
DateTime.ParseExact(dateString, "HHmm", CultureInfo.InvariantCulture);

Since you don't want the date portion, TimeSpan is your best bet.
CODE:
var time1 = "0800";
var time2 = "1200";
var time3 = "2359"; // 2400 is not a valid time
var ts1 = TimeSpan.ParseExact(time1, "hhmm", CultureInfo.InvariantCulture);
var ts2 = TimeSpan.ParseExact(time2, "hhmm", CultureInfo.InvariantCulture);
var ts3 = TimeSpan.ParseExact(time3, "hhmm", CultureInfo.InvariantCulture);
Console.WriteLine(ts1);
Console.WriteLine(ts2);
Console.WriteLine(ts3);
// Calculating time difference.
var tsDiff = ts1.Subtract(ts2);
Console.WriteLine(tsDiff);
OUTPUT:
08:00:00
12:00:00
23:59:00
-04:00:00

Related

How to convert a string to DateTime in a TextBox of a gridview [duplicate]

How do you convert a string such as 2009-05-08 14:40:52,531 into a DateTime?
Since you are handling 24-hour based time and you have a comma separating the seconds fraction, I recommend that you specify a custom format:
DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture);
You have basically two options for this. DateTime.Parse() and DateTime.ParseExact().
The first is very forgiving in terms of syntax and will parse dates in many different formats. It is good for user input which may come in different formats.
ParseExact will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. This way, you can easily detect any deviations from the expected data.
You can parse user input like this:
DateTime enteredDate = DateTime.Parse(enteredString);
If you have a specific format for the string, you should use the other method:
DateTime loadedDate = DateTime.ParseExact(loadedString, "d", null);
"d" stands for the short date pattern (see MSDN for more info) and null specifies that the current culture should be used for parsing the string.
try this
DateTime myDate = DateTime.Parse(dateString);
a better way would be this:
DateTime myDate;
if (!DateTime.TryParse(dateString, out myDate))
{
// handle parse failure
}
Use DateTime.Parse(string):
DateTime dateTime = DateTime.Parse(dateTimeStr);
Nobody seems to implemented an extension method. With the help of #CMS's answer:
Working and improved full source example is here: Gist Link
namespace ExtensionMethods {
using System;
using System.Globalization;
public static class DateTimeExtensions {
public static DateTime ToDateTime(this string s,
string format = "ddMMyyyy", string cultureString = "tr-TR") {
try {
var r = DateTime.ParseExact(
s: s,
format: format,
provider: CultureInfo.GetCultureInfo(cultureString));
return r;
} catch (FormatException) {
throw;
} catch (CultureNotFoundException) {
throw; // Given Culture is not supported culture
}
}
public static DateTime ToDateTime(this string s,
string format, CultureInfo culture) {
try {
var r = DateTime.ParseExact(s: s, format: format,
provider: culture);
return r;
} catch (FormatException) {
throw;
} catch (CultureNotFoundException) {
throw; // Given Culture is not supported culture
}
}
}
}
namespace SO {
using ExtensionMethods;
using System;
using System.Globalization;
class Program {
static void Main(string[] args) {
var mydate = "29021996";
var date = mydate.ToDateTime(format: "ddMMyyyy"); // {29.02.1996 00:00:00}
mydate = "2016 3";
date = mydate.ToDateTime("yyyy M"); // {01.03.2016 00:00:00}
mydate = "2016 12";
date = mydate.ToDateTime("yyyy d"); // {12.01.2016 00:00:00}
mydate = "2016/31/05 13:33";
date = mydate.ToDateTime("yyyy/d/M HH:mm"); // {31.05.2016 13:33:00}
mydate = "2016/31 Ocak";
date = mydate.ToDateTime("yyyy/d MMMM"); // {31.01.2016 00:00:00}
mydate = "2016/31 January";
date = mydate.ToDateTime("yyyy/d MMMM", cultureString: "en-US");
// {31.01.2016 00:00:00}
mydate = "11/شعبان/1437";
date = mydate.ToDateTime(
culture: CultureInfo.GetCultureInfo("ar-SA"),
format: "dd/MMMM/yyyy");
// Weird :) I supposed dd/yyyy/MMMM but that did not work !?$^&*
System.Diagnostics.Debug.Assert(
date.Equals(new DateTime(year: 2016, month: 5, day: 18)));
}
}
}
I tried various ways. What worked for me was this:
Convert.ToDateTime(data, CultureInfo.InvariantCulture);
data for me was times like this 9/24/2017 9:31:34 AM
Try the below, where strDate is your date in 'MM/dd/yyyy' format
var date = DateTime.Parse(strDate,new CultureInfo("en-US", true))
Convert.ToDateTime or DateTime.Parse
DateTime.Parse
Syntax:
DateTime.Parse(String value)
DateTime.Parse(String value, IFormatProvider provider)
DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)
Example:
string value = "1 January 2019";
CultureInfo provider = new CultureInfo("en-GB");
DateTime.Parse(value, provider, DateTimeStyles.NoCurrentDateDefault););
Value: string representation of date and time.
Provider: object which provides culture specific info.
Styles: formatting options that customize string parsing for some date and time parsing methods. For instance, AllowWhiteSpaces is a value which helps to ignore all spaces present in string while it parse.
It's also worth remembering DateTime is an object that is stored as number internally in the framework, Format only applies to it when you convert it back to string.
Parsing converting a string to the internal number type.
Formatting converting the internal numeric value to a readable
string.
I recently had an issue where I was trying to convert a DateTime to pass to Linq what I hadn't realised at the time was format is irrelevant when passing DateTime to a Linq Query.
DateTime SearchDate = DateTime.Parse(searchDate);
applicationsUsages = applicationsUsages.Where(x => DbFunctions.TruncateTime(x.dateApplicationSelected) == SearchDate.Date);
Full DateTime Documentation
string input;
DateTime db;
Console.WriteLine("Enter Date in this Format(YYYY-MM-DD): ");
input = Console.ReadLine();
db = Convert.ToDateTime(input);
//////// this methods convert string value to datetime
///////// in order to print date
Console.WriteLine("{0}-{1}-{2}",db.Year,db.Month,db.Day);
You could also use DateTime.TryParseExact() as below if you are unsure of the input value.
DateTime outputDateTimeValue;
if (DateTime.TryParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out outputDateTimeValue))
{
return outputDateTimeValue;
}
else
{
// Handle the fact that parse did not succeed
}
I just found an elegant way:
Convert.ChangeType("2020-12-31", typeof(DateTime));
Convert.ChangeType("2020/12/31", typeof(DateTime));
Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));
Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));
Convert.ChangeType("11/شعبان/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));
Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"
Put this code in a static class> public static class ClassName{ }
public static DateTime ToDateTime(this string datetime, char dateSpliter = '-', char timeSpliter = ':', char millisecondSpliter = ',')
{
try
{
datetime = datetime.Trim();
datetime = datetime.Replace(" ", " ");
string[] body = datetime.Split(' ');
string[] date = body[0].Split(dateSpliter);
int year = date[0].ToInt();
int month = date[1].ToInt();
int day = date[2].ToInt();
int hour = 0, minute = 0, second = 0, millisecond = 0;
if (body.Length == 2)
{
string[] tpart = body[1].Split(millisecondSpliter);
string[] time = tpart[0].Split(timeSpliter);
hour = time[0].ToInt();
minute = time[1].ToInt();
if (time.Length == 3) second = time[2].ToInt();
if (tpart.Length == 2) millisecond = tpart[1].ToInt();
}
return new DateTime(year, month, day, hour, minute, second, millisecond);
}
catch
{
return new DateTime();
}
}
In this way, you can use
string datetime = "2009-05-08 14:40:52,531";
DateTime dt0 = datetime.TToDateTime();
DateTime dt1 = "2009-05-08 14:40:52,531".ToDateTime();
DateTime dt5 = "2009-05-08".ToDateTime();
DateTime dt2 = "2009/05/08 14:40:52".ToDateTime('/');
DateTime dt3 = "2009/05/08 14.40".ToDateTime('/', '.');
DateTime dt4 = "2009-05-08 14:40-531".ToDateTime('-', ':', '-');
String now = DateTime.Now.ToString("YYYY-MM-DD HH:MI:SS");//make it datetime
DateTime.Parse(now);
this one gives you
2019-08-17 11:14:49.000
Different cultures in the world write date strings in different ways. For example, in the US 01/20/2008 is January 20th, 2008. In France this will throw an InvalidFormatException. This is because France reads date-times as Day/Month/Year, and in the US it is Month/Day/Year.
Consequently, a string like 20/01/2008 will parse to January 20th, 2008 in France, and then throw an InvalidFormatException in the US.
To determine your current culture settings, you can use System.Globalization.CultureInfo.CurrentCulture.
string dateTime = "01/08/2008 14:50:50.42";
DateTime dt = Convert.ToDateTime(dateTime);
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}, Hour: {3}, Minute: {4}, Second: {5}, Millisecond: {6}",
dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
This worked for me:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dt = DateTime.ParseExact("2009-05-08 14:40:52,531","yyyy-MM-dd HH:mm:ss,fff", provider);
Do you want it fast?
Let's say you have a date with format yyMMdd.
The fastest way to convert it that I found is:
var d = new DateTime(
(s[0] - '0') * 10 + s[1] - '0' + 2000,
(s[2] - '0') * 10 + s[3] - '0',
(s[4] - '0') * 10 + s[5] - '0')
Just, choose the indexes according to your date format of choice. If you need speed probably you don't mind the 'non-generic' way of the function.
This method takes about 10% of the time required by:
var d = DateTime.ParseExact(s, "yyMMdd", System.Globalization.CultureInfo.InvariantCulture);

Calculate average timespan

I am to calculate average of a set of time spans, where each time span is a subtraction between two dates.
DateTime a = GetStartDateTime();
DateTime b = GetEndDateTime();
var delta = b.Subtract(a).TotalDays;
Date format is like 22.08.2016 21:00:00
Is there any way to do this more rationally?
Also, I am curious why my delta is always like 0.26914351851851853, in other words why it is not integer?
UPDATE:
Here is example time spans:
23.08.2016 10:31:38 - 22.08.2016 21:00:00
24.08.2016 14:32:26 - 24.08.2016 21:00:00
17.08.2016 8:36:51 - 01.01.2016 21:00:00
17.08.2016 8:34:27 - 15.03.2016 21:00:00
Perform a simple mean calculation across the Ticks value of all your TimeSpans and create a new TimeSpan from the result. That will represent the average or mean TimeSpan. e.g.
var timeSpanList = new List<TimeSpan>();
var provider = CultureInfo.InvariantCulture;
timeSpanList.Add(
new TimeSpan(
DateTime.ParseExact("23.08.2016 10:31:38", "dd.MM.yyyy H:mm:ss", provider).Ticks -
DateTime.ParseExact("22.08.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
timeSpanList.Add(
new TimeSpan(
DateTime.ParseExact("24.08.2016 14:32:26", "dd.MM.yyyy H:mm:ss", provider).Ticks -
DateTime.ParseExact("24.08.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
timeSpanList.Add(
new TimeSpan(
DateTime.ParseExact("17.08.2016 8:36:51", "dd.MM.yyyy H:mm:ss", provider).Ticks -
DateTime.ParseExact("01.01.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
timeSpanList.Add(
new TimeSpan(
DateTime.ParseExact("17.08.2016 8:34:27", "dd.MM.yyyy H:mm:ss", provider).Ticks -
DateTime.ParseExact("15.03.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
var totalTicks = 0L;
foreach(var ts in timeSpanList)
{
totalTicks += ts.Ticks;
}
var avgTicks = totalTicks / timeSpanList.Count;
var avgTimeSpan = new TimeSpan(avgTicks);

how to convert timespan to string with format

I have timespan "1.00:00:11" and I would like to convert this to string:
"24:00" .As the code
DateTime date1 = Convert.ToDateTime("2014/12/12 14:37:56");
DateTime date2 = Convert.ToDateTime(("2014/12/13 14:37:59");
string minutes = (date2.Subtract(date1).TotalMinutes).ToString();
string result = TimeSpan.FromMinutes(Convert.ToDouble(minutes)).ToString();
I got result = "1.00:00:11".
How to change this result to (HH:mm).
And then I have a problem when I convert the string "24:00" to Datetime.
The Problem is:
The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.
Is there some function?
To get the amount of time in hh:mm:ss format, you could do something as like,
DateTime date1 = Convert.ToDateTime("2014/12/12 14:37:56");
DateTime date2 = Convert.ToDateTime(("2014/12/13 14:37:59"));
double totalSec = date2.Subtract(date1).TotalSeconds;
string result = string.Format("{0:00}:{1:00}:{2:00}", totalSec / 3600, (totalSec / 60) % 60, totalSec % 60);
And this produces the quantity of time in hh:mm:ss format, it is not hh:mm:ss part of any specific day.
So you cannot directly convert it into datetime type. For datetime type max of hh:mm:ss is just 23:59:59.
To get the hh:mm:ss part of the timespan you can do this,
string result = date2.Subtract(date1).ToString("hh\\:mm\\:ss");
Hope this helps...

Subtract TimeSpan bigger than 24H

I need to compare two TimeSpan values bigger than 24 hours.
For that I use the following code
string startTime = textBox1.Text;
string endTime = textBox21.Text;
TimeSpan startTimet = new TimeSpan(int.Parse(startTime.Split(':')[0]), // hours
int.Parse(startTime.Split(':')[1]), // minutes
0);
TimeSpan endTimet = new TimeSpan(int.Parse(endTime.Split(':')[0]), // hours
int.Parse(endTime.Split(':')[1]), // minutes
0);
TimeSpan duration = endTimet.Subtract(startTimet);
label29.Text = duration.ToString();
If the values aren't bigger than 24H it's all ok, but if I have a value bigger than 24h the TimeSpan will appear like DD.HH.MM.SS.
For example:
endTimet = 32:15
startTimet = 02:00
duration = 1.06:15:00
And what I really need is the normal format like HH:MM, assuming the hours are greater than 24, getting the expected 30:15
Can anyone help me here?
Regards
Perhaps with this workaround:
TimeSpan duration = TimeSpan.FromHours(30);
string result = string.Format("{0}:{1}"
, duration.TotalHours
, duration.Minutes); // 30:00
Noda Time to the rescue!
string s1 = "123:45";
string s2 = "234:56";
DurationPattern p = DurationPattern.CreateWithInvariantCulture("H:mm");
Duration d1 = p.Parse(s1).Value;
Duration d2 = p.Parse(s2).Value;
Duration diff = d2 - d1;
string result = p.Format(diff); // "111:11"

Convert Javascript time string to DateTime or TimeSpan in MVC Controller

How do I covert JavaScript string "5:00 PM" to DateTime or TimeSpan when it get send to the MVC controller. I am using
bootstrap-timepicker
// usage
<script type="text/javascript">
$('#timepicker1').timepicker();
</script>
Javascript payload
{
Skip: 0
Status: []
Take: 15
DueTime: "1:00 PM" // keep in mind that this is a string
}
Server Object would be something like
class TimeSheet
{
public TimeSpan DueTime;
}
Use DateTime.Parse. Convert on server(on controller) when your string would transmit with your time.
http://msdn.microsoft.com/ru-ru/library/system.datetime.parse(v=vs.110).aspx
Okay so I read everyhting wrong hence the deleted answer.. !
But I'm not giving up ;)
Your bootstrap-timepicker, will give you a time as this "1:00 PM".
But before that we are going to look on the serverside to see what we can parse into a datetime object.
This is C# for parsing datetime.
string dateString, format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "15/08/2000 16:58"
format = "dd/MM/yyyy HH:mm"
result = DateTime.ParseExact(dateString, format, provider);
Now as you se your string wont look like that I'm going to assume that you want todays date!
This is function I tend to use most of the times when converting, to 24H clock.
function ConvertTimeformat(str) {
var time = str;
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "PM" && hours < 12) hours = hours + 12;
if (AMPM == "AM" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
//Creating the todays date in the right format
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0!`
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var todaysdate = dd+'/'+mm+'/'+yyyy +" " ; //<--I added an extra space!
var hoursNminutes = sHours + ":" + sMinutes
//CREATE THE RIGHT FORMAT FOR DATE.PARSEXACT "dd/MM/yyyy HH:mm"
var dateToParse = todaysdate + hoursNminutes
return dateToParse;
}
To Use the function do like this!
//Call it and provide your bootstrap time. And make it return to a variable
var dateToBeSentToServer = ConvertTimeformat("1:00 PM");
//OR With the bootstraptime as a variable
var dateToBeSentToServer = ConvertTimeformat(timevariable);
Now you can send dateToBeSentToServer to your serverside for parsing!

Categories