I have two concatenated values such as
string BreakOut = "10:15 Mintes";
string BreakIn = "10:30 Minutes";
I want result as
Total=15 Minutes
It is a time difference calculation. But values are not in a time format it is in a string format. How can I do this. Please suggest a way. I tried like
TimeSpan span=Convert.ToDateTime(BreakOut ).Subtract(Convert.ToDateTime(BreakIn ));
There is no point to parse them to DateTime since they are time interval. TimeSpan would be better choice since it is exactly what this for.
If Mintes is typo and your values are always the same standard format, you can easily split them with white space and then parse to TimeSpan.
For example;
var BreakOut= "10:15 Minutes";
var BreakIn = "10:30 Minutes";
BreakOut = BreakOut.Split(new string[]{" "},
StringSplitOptions.RemoveEmptyEntries)[0];
BreakIn = BreakIn.Split(new string[] { " " },
StringSplitOptions.RemoveEmptyEntries)[0];
var ts1 = TimeSpan.Parse(BreakOut, CultureInfo.InvariantCulture);
var ts2 = TimeSpan.Parse(BreakIn, CultureInfo.InvariantCulture);
var difference = ts2 - ts1;
Console.WriteLine("{0} minutes", difference.TotalMinutes); // 15 Minutes
Here a demonstration.
if your values always refers to the same day,
you can use something like that :
string BreakOut="10:15" ;
string BreakIn ="10:30";
double res =DiffInMinutes(BreakIn, BreakOut);
//Total=15 Minutes
public static double DiffInMinutes(string _BreakIn, string _BreakOut)
{
double diff = 0;
string[] BreakIn = _BreakIn.Split(':');
string[] BreakOut = _BreakOut.Split(':');
//timeSpan instanciated with Hours/minutes/seconds
TimeSpan TimeElapsed = new TimeSpan(int.Parse(BreakOut[0]) - int.Parse(BreakIn[0]), int.Parse(BreakOut[1]) - int.Parse(BreakIn[1]), 0);
diff = TimeElapsed.TotalMinutes;
return diff;
}
I downvoted your question, but maybe you really dont know that there is TimeSpan.Parse
string breakOut = "10:15 Minutes";
string breakIn = "10:30 Minutes";
string cleanBreakIn = breakIn.Split(' ')[0];
string cleanBreakOut = breakOut.Split(' ')[0];
TimeSpan total = TimeSpan.Parse(cleanBreakIn) - TimeSpan.Parse(cleanBreakOut);
Related
I want to be able to calculate the time in hours and minutes elapsed between, say, 12:35pm 02/13/2016 to 1:45pm 02/14/2016, but can't figure out the correct format to input it.
EDIT: Should add that the span between the times will be stored in an arraylist, one span per customer.
Basically, you need something like this:
var dateA = new DateTime(2016,2,13,12,35,0);
var dateB = new DateTime(2016,2,14,1,45,0);
var timespan = dateB - dateA;
var hours = timespan.Hours;
bar minutes = timespan.Minutes;
Here's how I would go about it:
Func<string, DateTime?> tryParse = t =>
{
DateTime output;
if (DateTime.TryParseExact(
t,
new [] { "h:mmtt MM/dd/yyyy" },
System.Globalization.CultureInfo.CurrentCulture,
System.Globalization.DateTimeStyles.AssumeLocal,
out output))
{
return output;
}
return null;
};
var dt1 = tryParse("12:35pm 02/13/2016");
var dt2 = tryParse("1:45pm 02/14/2016");
TimeSpan? ts = null;
if (dt1.HasValue && dt2.HasValue)
{
ts = dt2.Value.Subtract(dt1.Value);
}
if (ts.HasValue)
{
Console.WriteLine(
String.Format(
"{0} hours & {1} minutes",
ts.Value.Hours,
ts.Value.Minutes));
}
I have a string called value with 1899-12-30 01:30:00
I want to get 01:30 into a seperate string, I have tried to use substring but it keeps giving me an error that the startindex cannot be less than zero, can someone tell me what im doing wrong?
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
if (dtExcelData.Rows.Count > 0)
{
foreach (DataRow rw in dtExcelData.Rows)
{
//Creates StaffID
rw["StaffID"] = "00" + rw["Host Key of Staff"].ToString();
//Get duration out of DateTime
string Value = rw["Taught Periods Distinct as duration"].ToString();
string Duration = Value.Substring(Value.Length - 10, 5);
rw["Taught Periods Distinct as duration"] = Duration.ToString();
}
}
Debugging it says:
Duration = "01:30" Type String
Value = "30/12/1989 01:30:00" Type String
Value.Length = 19 Type int
rw["Taught periods as distinct as duration"] = "30/12/1989 01:30:00" Type object {string}
First add a break point and see the value of Value, it seems like there is invalid value in your variable.
To extract out 01:30 into a separate string, a better approach would be to use DateTime parsing. Because your string is a valid DateTime value. Use
DateTime parsedDateTime;
string Duration = null;
if (!DateTime.TryParseExact("1899-12-30 01:30:00", //or rw["Taught Periods Distinct as duration"].ToString();
"yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out parsedDateTime))
{
Console.WriteLine("Invalid date");
}
else
{
Duration = parsedDateTime.ToString("HH:mm", CultureInfo.InvariantCulture);
}
In fact, you want to extract the time (hour + minute) from your date.
For this, I recommend not to do string conversions. Instead, better use a more direct approach by directly using DateTime, like this:
DateTime Value = rw["Taught Periods Distinct as duration"];
rw["Taught Periods Distinct as duration"] = Value.TimeOfDay ;
this works:
string Value = "Taught Periods Distinct as duration".ToString();
string Duration = Value.Substring(Value.Length - 10, 5);
and also:
string Value2 = "1899-12-30 01:30:00";
string Duration2 = Value2.Substring(Value2.Length - 10, 5);
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"
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
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!