In the below code i will get a list of time span values. I need to add all the time span values and that value has to be stored in string.How to achieve this i tried a lot but I can't find answer for this.
Thanks in Advance.
List<TimeSpan> objList = new List<TimeSpan>();
string totalIntervalTime = string.Empty;
private void Resume_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox2.Text))
{
textBox3.Text = DateTime.Now.ToLongTimeString();
//objPausetmr.Tick += new EventHandler(objPausetmr_Tick);
//objPausetmr.Stop();
tmrObj.Start();
DateTime pausetime = Convert.ToDateTime(textBox2.Text);
DateTime startTime = Convert.ToDateTime(textBox3.Text);
TimeSpan difference = pausetime - startTime;
string intervalDifference = difference.ToString();
richTextBox1.Text = intervalDifference;
TimeSpan tltTime = TimeSpan.Zero;
objList.Add(difference);
foreach (TimeSpan tmVal in objList)
{
tltTime.Add(tmVal);
}
totalIntervalTime = tltTime.ToString();
//MessageBox.Show(interval_Time.ToString());
}
else
{
MessageBox.Show("Please set the Pause time");
}
}
Assuming you want to add values of all time spans into single time span.
DateTime and TimeSpan are immutable structs. All operations using them return new instances. So you need to store result of operation in a TimeSpan value (normally just updating exisintg one is fine)
var totalTime = TimeSpan.Zero;
foreach (TimeSpan currentValue in objList)
{
totalTime = totalTime + currentValue;
}
Usage of + covered in details in TimeSpan.Addition Operator MSDN article.
Alternatively you can use Enumerable.Aggregate:
var totalTime = objList.Aggregate(
(accumulatedValue,current) => accumulatedValue + current);
You can try something like
string s = String.Join(",",objList.Select(x => x.ToString()));
Have a look at
String.Join Method
Enumerable.Select
Using objList.Select(x => x.ToString()) you can determine the format output you want
Span.ToString Method (String)
Related
I have an API which will accept timezone offset as string. I need to convert the timezone to TimeSpan and add the timespan with the data i have which is in UTC. Here is what i'm trying.
private bool TryGetHrAndMinFromTimeZone(string timeZone, out TimeSpan result)
{
try
{
var isPositive = !timeZone.StartsWith("-");
var hrAndMin = string.Concat(timeZone.Where(x => x != '-' && x != '+')).Split(':');
var hr = int.Parse(hrAndMin[0]);
var min = int.Parse(hrAndMin[1]);
result = isPositive ? new TimeSpan(hr, min, 0) : new TimeSpan(-hr, -min, 0);
return true;
}
catch (Exception)
{
throw new Exception(string.Format("Provided TimeZone '{0}' is Invalid ", timeZone));
}
}
Is there any better option to do it?
you can try
TimeSpan.TryParse("-07:00", out TimeSpan ts) //for -07:00
TimeSpan.TryParse("07:00", out TimeSpan ts) //for +07:00
for more information https://learn.microsoft.com/en-us/dotnet/standard/datetime/converting-between-time-zones#converting-datetimeoffset-values
The DateTimeOffset type can parse offsets of this format using the zzz specifier. Thus you can write a function such as the following:
static TimeSpan ParseOffset(string s)
{
return DateTimeOffset.ParseExact(s, "zzz", CultureInfo.InvariantCulture).Offset;
}
Another approach, you can parse with TimeSpan.ParseExact if you strip off the sign first and handle it yourself:
static TimeSpan ParseOffset(string s)
{
var ts = TimeSpan.ParseExact(s.Substring(1), #"hh\:mm", CultureInfo.InvariantCulture);
return s[0] == '-' ? ts.Negate() : ts;
}
Or, as Manish showed in his answer, you can let TimeSpan.Parse attempt to figure out the string. It works if you remove the + sign first.
static TimeSpan ParseOffset(string s)
{
return TimeSpan.Parse(s.Replace("+", ""), CultureInfo.InvariantCulture);
}
I can't seem to get my head around this but what would be the best approach for displaying a list of upcoming events?
At the moment I have a list of json events being displayed. All these events have a specific date on them.
2016-04-01T13:15:00
Most of the events have passed so i do not need to have them shown. How would i go about only showing the upcoming events?
The main thing I cant figure out is how to get todays date...
This is the code I used to display the events.
async void PopulateTableWithData()
{
var service = new Data.RestService();
var response = await service.GetEventItemsAsync();
Debug.WriteLine("JSON RESULTS FOUND: " + response.Count + "events");
listView.ItemsSource = response; // Display data in listview
/**ITEM SELECTED EVENT**/
listView.ItemSelected += (sender, e) =>
{
var i = (listView.ItemsSource as List<EventItems>).IndexOf(e.SelectedItem as EventItems);
string title = response[i].Title;
string description = response[i].EventDescription;
string location = response[i].EventLocation;
string startTime = response[i].EventStartTime;
string endTime = response[i].EventEndTime;
string rowKey = response[i].RowKey;
Navigation.PushAsync(new EventsWebviewPage(title, description, location, startTime, endTime, ReplaceString(rowKey, " ", "%20")));
};
}
Would I have to use some form of DateTime?
Can anyone give me some guidance?
Thanks
EDITED
async void PopulateTableWithData()
{
var service = new Data.RestService();
var response = await service.GetEventItemsAsync();
Debug.WriteLine("JSON RESULTS FOUND: " + response.Count + "events");
//listView.ItemsSource = response; // Display data in listview
for(int i = 0; i < response.Count; i++)
{
// Split raw json date
string[] splitRawDateTime = response[i].EventEndTime.Split('T');
string[] splitRawDate = splitRawDateTime[0].Split('-');
string eventYear = splitRawDate[0];
string eventMonth = splitRawDate[1];
string eventDay = splitRawDate[2];
// Compare dates and display events according to date
DateTime currentDateTime = DateTime.Now;
DateTime eventDateTime = new DateTime(int.Parse(eventYear), int.Parse(eventMonth), int.Parse(eventDay), 0, 0, 0);
int compareDates = DateTime.Compare(eventDateTime, currentDateTime);
List<EventItems> upcomingEvents = new List<EventItems>();
if (compareDates < 0)
{
Debug.WriteLine("Event date {0} is earlier then current date {1}", eventDateTime, currentDateTime);
}
else
{
Debug.WriteLine("Event date {0} is later then current date {1}", eventDateTime, currentDateTime);
upcomingEvents.Add(response[i]);
}
listView.ItemsSource = upcomingEvents;
}
}
}
I have just tried the above code and it seems to be working but how do I only display the upcoming events?
I believe its an issue with my placement of
listView.ItemsSource = response;
I know im probably doing something wrong here. Can anyone help?
You can get the current date and time by using DateTime.Now
You can also create a DateTime object from a string representation of a date by using one of the DateTime.Parse() functions. Then you can compare the two dates by using comparison operators: <, <=, >, >=, ==
Edit: You could try it his way:
async void PopulateTableWithData()
{
var service = new Data.RestService();
var response = await service.GetEventItemsAsync();
Debug.WriteLine("JSON RESULTS FOUND: " + response.Count + "events");
//listView.ItemsSource = response; // Display data in listview
//Instantiate the list of upcoming events before the loop
List<EventItems> upcomingEvents = new List<EventItems>();
for(int i = 0; i < response.Count; i++)
{
// Split raw json date
string[] splitRawDateTime = response[i].EventEndTime.Split('T');
string[] splitRawDate = splitRawDateTime[0].Split('-');
string eventYear = splitRawDate[0];
string eventMonth = splitRawDate[1];
string eventDay = splitRawDate[2];
// Compare dates and display events according to date
DateTime currentDateTime = DateTime.Now;
DateTime eventDateTime = new DateTime(int.Parse(eventYear), int.Parse(eventMonth), int.Parse(eventDay), 0, 0, 0);
int compareDates = DateTime.Compare(eventDateTime, currentDateTime);
if (compareDates < 0)
{
Debug.WriteLine("Event date {0} is earlier then current date {1}", eventDateTime, currentDateTime);
}
else
{
Debug.WriteLine("Event date {0} is later then current date {1}", eventDateTime, currentDateTime);
//Populate the list of upcoming events
upcomingEvents.Add(response[i]);
}
}
//Display the list of upcoming events
listView.ItemsSource = upcomingEvents;
}
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 know this has been asked before but i couldn't figure out how to get the answers given working for my particular example. This is a WPF application written in C# and i'm trying to remove a number of minutes from a timespan.
So far i've got the application to figure out the duration by removing a Start Time from a Finish Time, but what i'm trying to do now is remove the number of minutes the user has entered into the form.
Here's the code so far
private void testcal_Click(object sender, EventArgs e)
{
string startTime = teststart.Text;
string finishTime = testfinish.Text;
// Trying to deduct this lunchTime var from the duration TimeSpan
string lunchTime = testlunch.Text;
TimeSpan duration = DateTime.Parse(finishTime).Subtract(DateTime.Parse(startTime));
testlabel.Text = duration.ToString(#"hh\:mm");
}
Edit - Updated to include private void
Are you asking how to subtract minutes from a TimeSpan?
If so try something like
TimeSpan ts = new TimeSpan().Subtract(TimeSpan.FromMinutes(30));
With user input it would be.
string startTime = teststart.Text;
string finishTime = testfinish.Text;
string lunchTime = testlunch.Text;
TimeSpan duration = DateTime.Parse(finishTime).Subtract(DateTime.Parse(startTime)).
Subtract(TimeSpan.FromMinutes(Int32.Parse(lunchtime)));
DateTime selectedDate = DateTime.Parse("10/09/2021");
DateTime now = DateTime.Now;
TimeSpan subtract = now - selectedDate;
subtract -= new TimeSpan(7, 0, 0, 0);
I am looking for a C# solution that will allow me to iterate backwards over a date.
Starting at the current date or provided date I would like to loop over the date subtracting one day each time through the loop for a given number of days. It should of course be able to detect when the month has changed or it is a leap year etc., and return the date in MM-DD-YYYY format.
Should be easy enough:
var givenNumberOfDays = 30;
for( DateTime day = DateTime.Now; day > DateTime.Now.AddDays( -givenNumberOfDays); day = day.AddDays(-1) )
{
//perform your logic here
var dateInCorrectFormat = day.ToString("MM-dd-yyyy");
}
public IEnumerable<DateTime> Dates(int nDays)
{
DateTime dt = DateTime.Now;
yield return dt;
for(int i=0;i<nDays-1;i++)
{
dt = dt.AddDays(-1);
yield return dt;
}
}
foreach (var dt in Dates(10))
{
Console.WriteLine(dt.ToString("MM-dd-yyyy"));
}
this would iterate backwords:
class Program
{
static void Main(string[] args)
{
DateTime myDate = DateTime.Now;
for (int i = 0; i < 10; i++)
{
Console.WriteLine(myDate.AddDays(-i).ToString("MM-dd-yyyy"));
}
}
}
You can use Dateadd function, that let you add or subtract an interval of time to/from a date and returning the resulting date.
In your case, the interval is "d" (day).
See here.