format TimeSpan summary in stimulsoft - c#

I'm creating simple table report with column of TimeSpan type.
I'm summing its values, which leads into values bigger than 24 hours, into Text componnent.
{SumTime(DataBand1,Records.time)}
I'm trying to format Text field like HH:mm:ss, but for 25 hours it gives me 01:00:00 (or 1.01:00:00 with general formatting) instead of 25:00:00 what is my goal.
Edit: The problem is not how to format timespan, but how to associate formatted value into Stimulsoft's Text component.

The Hours property has a maximum of 24h. You could format it yourself using String.Format and TimeSpan.TotalHours:
string text = string.Format("{0}:{1}:{2}",
(int) Records.time.TotalHours, // TotalHours is double
Records.time.Minutes,
Records.time.Seconds);

I know this is kind of an old question, but I stumbled upon it looking for a solution myself. Having done some digging, here's what I've come up with:
Assuming you already have a timespan variable (either setting it in the datasource, or having a variable set with DateDiff), you can format it with the following:
{string.Format("{0}:{1}:{2}",
(int) Variable1.TotalHours,
Variable1.Minutes,
Variable1.Seconds)}
Lets say you have two different fields (named Date1 and Date2) that you need to get the difference of, and don't feel like putting it into a variable:
{string.Format("{0}:{1}:{2}",
(int) DateDiff(Date2,Date1).TotalHours,
DateDiff(Date2,Date1).Minutes,
DateDiff(Date2,Date1).Seconds)}

Related

How to Use DateTime.Now function

Currently I am using DateTime.Now.ToLongDateString() to set a date property, although I would like to be more detailed in the date. The purpose is to perform a sort based on the date of an item, and this currently will give a date in the format Thursday, July 4, 2013. If several items have this same date property on the same day, the sort is not performed. Is there a function of DateTime.Now that will allow a date property with seconds?
To note, the day and year must still be included because the sort may happen over several days, in several years, but there may also be several instances of the item on the same day. What recommendation would you suggest, or is there a better way to go about this? Also, this must work for any culture and any time zone.
EDIT
In my MainPage I am populating a ListBox named Recent with a collection of pictures. From my Settings page, a user may choose ascending or descending sort order, and based on this the collection must be sorted accordingly before populating the listbox.
MainPage.xaml.cs
protected override void OnNavigatedTo(NavigationEventArgs e)
{
ObservableCollection<Selfie.Models.Picture> listItems = new ObservableCollection<Selfie.Models.Picture>(PictureRepository.Instance.Pictures);
if (Settings.AscendingSort.Value)
{
listItems.OrderBy(x => x.DateTaken);
Recent.ItemsSource = listItems;
}
else
{
listItems.OrderByDescending(x => x.DateTaken);
Recent.ItemsSource = listItems;
}
}
I have a class that Serializes and Deserializes the DateTime as a property of the Picture, which is applied to DateTaken, which I am trying to sort by.
EDIT 2
Okay,
you need to use the result of the OrderByDescending function.
// listItems remains unaffected.
var sorted = listItems.OrderByDescending();
Many functions, especially extensions that act upon structures with a level of immutablity, do not effect the source. The pure function should be used in a "fluent" style. The return value needs to be assinged to be utilized.
So, you need to do,
Recent.ItemsSource = listItems.OrderBy(x => x.DateTaken).ToList();
Its worth considering a tool like Resahrper to catch issues like this. They are common with the DateTime Add functions.
EDIT
Because you are working in a multi cultural situation, ensure that all your dates are instantiated and stored with a UTC kind, this is going to help you massively. Even if working in a single time-zone but sorting across Day light Saving Time boundries.
Instead of DateTime.Now use DateTime.UtcNow and leave all values as UTC DateTimes until they are exported or presented on the GUI.
This way you will be comparing apples with apples, and your sorting will work as expected and your data will be much easier to debug.
If you start to do anything sophisticated, you're going to find the cracks in .Nets DateTime implementation. It's considering using Jon Skeet and other's work on noda time which should overcome many pit falls.
This will not work across time zones, calendars or just Day light Saving
If you did need a sortable String for some reason, use DateTime.Now.ToString("o"); this makes a string with in the Round-trip format,
yyyy-MM-ddTHH:mm:ss.fffffff
which is nicely sortable, including a fractional portion. Assuming all the values come from the same timezone and calendar.
Just sort by DateTime.Now directly, without converting to a string. If you store the DateTime directly in your property, this will not be an issue.
The DateTime type supports dates and times down to the tick.
You can also format the date however you choose for display, but it is typically better to store, internally, the actual DateTime.
Just use the DateTime object directly. It will give you the day, month, year, hour, mins, seconds which is enough to do your sort.
For example: -
var foo = collection.OrderBy(d => d.Date);
The DateTime.Now.ToString() method will give you a string formatted with everything included.
But as #SimonBelanger pointed out, you should probably sort directly on the DateTime, not on the string representation.
If you need to serialize the date, as opposed to just sorting on the DateTime object, you can try converting it to unix time (the number of milliseconds since the start of the Unix Epoch).
stackoverflow.com/questions/9814060/...
Since it's just a long, you can sort it easily as well as storing it in a string or long or whatever.
If you can sort by the DateTime directly as Reed stated do that. However, if you can't, you'll want to string it out a very specific way. Maybe something like this:
date.ToString("YYYYMMddHHmmss")
because to sort dates in a character fashion you need to sort the parts of the date in the right order.
You can use DateTime.Now.ToString("YYYYMMddHHmmss") or DateTime.Now.Ticks
If you Add this piece of code DateTime.Now.ToString(); it will print 7/4/2013 10:05:18 PM ,
If you Add string time = DateTime.Now.ToString("hh-mm-ss"); it will print(10-07-36).
In the tostring method you can format the date based on your requirement.

C# how to add a column of hours which are in string format

working hours of a person in my program will be shown like this:
As they are in string format how can I calculate the total hours of a person?
You need to store the values as TimeSpans, so you can perform calculations on them, and only convert to strings for display purposes.
You indeed need to store the values as TimeSpan instances.
But maybe they are given to you as strings. In that case you can convert them to TimeSpan using TimeSpan.Parse(), see http://msdn.microsoft.com/en-us/library/system.timespan.parse.aspx

Retrieve format of date from date value

I am receiving some data into a variable of type object. In certain cases this data are date values. For that data, I would like to convert this to a string and return it in the same format as it was passed. In some cases, the object could be a datetime, in others a date only or time only values.
As soon as I convert the object to a date or a string, it is obviously given a time of midnight which in my scenario may be a valid time (so I cannot test to see if the time is midnight in which case I could deduce that it would have been a date only date value, nor can I use regex on it as there will always be a time element).
Intellisense shows me it correctly, ie in the format I am wishing to return the value.
Is there an easy way to achieve this (hopefully without using reflection)
Many thx
Simon
Your question is a little unclear but I think you're looking for something like this:
DateTime result;
if (DateTime.TryParse(value, out result))
{
// use result here
}
In the above code value is a string that represents the data coming in. The code will only enter the if block if the string is a valid DateTime. At which point you can do the processing you need on it.
Im not sure i understand the question but i would recommend you to take a look at this conversion example on MSDN, and see the Documentation of the DateTime Structur it contains a lot of Conversion/Formatting Methods i hope it helps.
There are many way to do formatting on the datetime and one of the simple way is fetch the data from the required table in the desired format. Like here you need to display the date and if you your format is dd/MM/yyyy then try this
select Convert(varchar(10),StartDate,103) as StartDateformat from table where filtername=#filtername
use this link to find other format Cast and Convert
From local variable to DateTime Conversion
DateTime todateformat = Convert.ToDateTime(txttodate.Text.Trim());
From DateTime to local variable Conversion in specific format
string startdate = todateformat.ToString("dd/MM/yyyy hh:mm:ss");

Parsing dates without all values specified

I'm using free-form dates as part of a search syntax. I need to parse dates from strings, but only preserve the parts of the date that are actually specified. For instance, "november 1, 2010" is a specific date, but "november 2010" is the range of dates "november 1, 2010" to "november 30, 2010".
Unfortunately, DateTime.Parse and friends parse these dates to the same DateTime:
DateTime.Parse("November 1, 2010") // == {11/1/2010 12:00:00 AM}
DateTime.Parse("November, 2010") // == {11/1/2010 12:00:00 AM}
I need to know which parts of the DateTime were actually parsed and which were guessed by the parser. Essentially, I need DateTime.Parse("November, 2010") == {11/-1/2010 -1:-1:-1}; I can then see that the day portion is missing and calculate the range of dates covering the whole month.
(Internally, C# has the DateTimeParse and DateTimeResult classes that parse the date and preserve exactly the information I need, but by the time the date gets back to the public interfaces it's been stripped off. I'd rather avoid reflecting into these classes, unless that's really the only route.)
Is there some way to get DateTime.Parse to tell me which format it used to parse the date? Or can the returned DateTime have placeholders for unspecified parts? I'm also open to using another date parser, but I'd like it to be as reliable and locale-flexible as the internal one. Thanks in advance.
EDIT: I've also tried ParseExact, but enumerating all of the formats that Parse can handle seems nearly impossible. Parse actually accepts more formats than are returned by DateTimeFormatInfo.GetAllDateTimePatterns, which is about as canonical a source as I can find.
You could try using TryParseExact(), which will fail if the data string isn't in the exact format specified. Try a bunch of different combinations, and when one succeeds you know the format the date was in, and thus you know the parts of the date that weren't there and for which the parser filled in defaults. The downside is you have to anticipate how the user will want to enter dates, so you can expect exactly that.
You could also use a Regex to digest the date string yourself. Again, you'll need different regexes (or a REALLY complex single one), but it is certainly possible to pull the string apart this way as well; then you know what you actually have.
Parse parses a whole lot of stuff that no sane person would enter as a date, like "January / 2010 - 21 12: 00 :2". I think you'll have to write your own date parser if you want to know what exactly the user entered.
Personally I would do it like KeithS suggested: Parse the string with Parse and only call your own parse function if there's a 0 in one of the fields of the DateTime object. There are not that that possibilities you need to check for, because if the day is 0, the time will be 0, too. So start checking year, month, day, etc..
Or simply instruct the user to use specific formats you recognize.
Essentially, I need
DateTime.Parse("November, 2010") ==
{11/-1/2010 -1:-1:-1}; I can then see
that the day portion is missing and
calculate the range of dates covering
the whole month.
What you want is an illegal DateTime because you cannot have a negative hours/seconds/minute/day values. If you want to return something else other then a legal DateTime you have to write your own method which does NOT return a DateTime.
Is there some way to get
DateTime.Parse to tell me which format
it used to parse the date? Or can the
returned DateTime have placeholders
for unspecified parts? I'm also open
to using another date parser, but I'd
like it to be as reliable and
locale-flexible as the internal one.
Take a look here http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
You are going to have to manually keep track of what is entered to do this task. The only solution is to make sure the input is in the correct format.
I used this method that goes back to the original string in order to check for existence of the day and the year:
For days, the original string must contain a 1 as integer if the day was specified. So, split the string and look for a 1. The only exception occurs when the month is January (#1 month), so you should check for two 1s or a 1 and "January" or "Jan" in the original string.
For years, the original string must contain a number that can be a year (say, from 1900 to 2100). Other possibilities may be the use of an apostrophe, or things like 02-10-16, which you can recognize by the fact that there are exactly three numbers.
I know that this is pretty heuristic, but it's a fast and simple solution that works in most cases. I coded this algorithm in C# in the DateFinder.DayExists() and DateFinder.YearExists() methods in the sharp-datefinder library.

Numeric Format String : double to time

I have a double value in seconds and i would like to use a Numeric Format String to display it as mm:ss or hh:mm:ss.
Is this possible? Havent found anything about it on MSDN?
The reason is that we use a Telerik Chart that displays our data and since I cant change the uderlying format I have to hook the format string into their chart api.
Thanks in advance
Johan
You're looking for the TimeSpan class.
Use the following:
var ts = new TimeSpan(0, 0, 0, (int)doubleValueOfSeconds, 0);
Of course you might want to consider more accurate rounding of the double value, rather than truncation as in my example.
Take a look at TimeSpan on MSDN to get the string value, though the simplest current culture-specific thing would be TimeSpan.ToString().
UPDATE to updated question:
You can't directly format a number of seconds to a date and time. Formatting is essentially string manipulation, and you need it to do some maths before that formatting happens.
Use my example above, then call TimeSpan.ToString(formatString); to get the string values to give to the control.
That's assuming you haven't simply missed something. I personally think the Telerik controls are waaaay to complex, but I'm sure they'll have formatting built-in. Essentially, write code using my example above to create the data with timespans, then use the inbuilt format string to tell the control how to format the timespan for the given data series.

Categories

Resources