How to convert these PHP functions to C#? - c#

In PHP, you can write the following:
date_default_timezone_set("UTC");
How do I do I write this in C#?
Also, how do I write this:
declare(ticks=1);
in C#?

In c#, the timezone is built into the DateTime structure, so you should not need to set the default. Instead when you are manipulating DateTime instances you use the UTC version of methods. For example, in the constructor you can specify if the date supplied is local or UTC.
With regards to the second question, are you just wanting the syntax of
int ticks = 1; // or
var ticks = 1;
If you are trying to add a time period to a date, you should use a TimeSpan, along the lines of:
TimeSpan ticks = new TimeSpan(1);

Related

How to properly parse DateTime string

I've got input date time strings which look like this: 2015-01-28 17:55:43. The problem is that they are in UTC+8 (or some other shift). I need those strings parsed and processed properly into UTC, regardless of the timezone where the software runs.
My problem is that DateTime.Parse returns local time, not UTC time, and I don't see a way to specify shift when parsing the string.
My current solution to this looks something like this:
add.LastUpdatedTime = new DateTime((DateTime.Parse(text) - new TimeSpan(0, 8, 0, 0)).Ticks,DateTimeKind.Utc);
This is ugly, and I'm not sure that it will work well in all circumstances.
Is there a better way of doing this?
Given that you have a local time and an offset, I'd suggest representing that in DateTimeOffset. So:
DateTime localTime = DateTime.ParseExact(...);
DateTimeOffset offsetTime = new DateTimeOffset(localTime, offset);
Then you still know the local time, but you can get the UTC equivalent when you want it. Basically it preserves all the information you have.
As an alternative, you could use Noda Time which represents the same information in OffsetDateTime. You'd use a LocalDateTimePattern to parse the value to a LocalDateTime, then use the WithOffset method to convert to an appropriate OffsetDateTime.
Write a sample program, and output the following:
Console.WriteLine(DateTime.Now.ToString("o"));
Look at that format, and use it as a template for patching up the string times coming in. For even more viable string options, look at DateTime.ToString Method ... I'll bet some variant on there will work out for you (e.g., play around with a format having "zzz" on the end, which will generate the UTC offset for a local time, e.g., "HH:mm:ss.ffffzzz" as shown in the page linked).
Also look at DateTime.Parse Method in the examples ... notice the string "2008-09-15T09:30:41.7752486-07:00" containing a UTC offset of -7 (America/Denver) indicated as being valid for parsing.

How to convert int/string in h.(fraction of day) format to Timespan

So I have a webapp that calls a SQL package function that returns a number type in the form of d.(fraction of a day[up to two decimal places]).
So for example, 1.5 would translate to one and a half days.
I want to convert it to a timespan. From working with C#, there seems to be a fair amount of useful library functions, so I was hoping there might be some function I could call and do the conversion in a line or two. However, the closest thing I could find was Parse. However it only has an hour format of 0-23 hours rather than something that takes in fractions of days.
So is there some other function I could use or could I use some sort of hackery like this:
culture = new CultureInfo("d.(hh*24)"),
TimeSpan ts = TimeSpan.Parse(value, culture);
Try this:
TimeSpan ts = TimeSpan.FromDays(value);

How can I format date using json.SerializerSettings.Converters to look like 1288323623006

I am currently using the following date filter in my WebAPI application:
json.SerializerSettings.Converters.Add(
new IsoDateTimeConverter { DateTimeFormat = "dd-MM-yyyy hh:mm" });
I started to use this as my front end could not understand the dates. If I remember correctly it was due to the way milliseconds were formatted with too many digits.
What I need is to get the date into a format like this:
1288323623006
Can someone suggest how I can do this using the serializer. Is this different from the default?
You don't want to use IsoDateTimeConverter at all - you possibly want to use JavaScriptDateTimeConverter. That will convert it into new Date(...) with the right value - but I believe it really will include the new Date(...) part. If you don't want that, you'll probably need to write your own converter.
It shouldn't be too hard to write a converter - although you need to decide how to handle the different kinds of DateTime. For example, if you're asked to convert a DateTime with a Kind of Unspecified, do you want to assume it's actually already in UTC, or already in the system local time zone, or something else?
Once you've got an appropriate "instant" in time, you just need to find the number of milliseconds between that and the Unix epoch (1st January 1970 00:00:00, UTC) and convert that number of milliseconds into a string.
I think that's what you want
private static readonly long DatetimeMinTimeTicks = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;
long b = (long)((Calendar1.SelectedDate).ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000;

C#, how do I make a clock work with added hours?

Using Visual Studio 2008 (C#) I have to make a working clock (digital) with the current time zone hour, and a few more with different time zones, like new york, etc.
inside the form I put 2 labels (for the clocks) and a timer, inside the timer I put this code:
timer1.Interval = 1000;
label1.Text = DateTime.Now.ToLongTimeString();
DateTime myDateTime = DateTime.Now;
TimeSpan myTimeSpan = new TimeSpan(2, 0, 0);
DateTime myDateTime8 = myDateTime + myTimeSpan;
label2.Text = ("" + myDateTime8);
the part with the timespan does add 2 hours to the clock, however, instead of just the actually clock I also get the date on it's left, like for example:
"17-05-2011 22:38:00"
I need to know how can I add/subtract hours and only show the clock.
Instead of adding a timespan, simply call the AddHours method:
myDateTime.AddHours(2).ToLongTimeString();
myDateTime.ToShortTimeString() will return you only time
or as Tejs mentioned you can use ToLongTimeString() that I guess more suits your requirement.
For adding or subtracting hours you can use dateTime.AddHours(even hours in negative) or for subtracting you can also use dateTime.Subtract(time to subtract)
Using the .ToString() method of the timespan method allows you to output the date in any format you want. See http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
For your time zone needs, use an approach similar to the one suggested in this MSDN article. Notably:
Use ConvertTimeToUtc to get UTC time before performing any arithmetics.
Perform required arithmetics.
Convert back to local time using TimeZoneInfo.ConvertTime.
To get just the time part of a DateTime, use DateTime.ToShortTimeString(). Note that this is culture-aware, so if you want a fixed format, consider using DateTime.ToString() to specify a format.

How do you calculate accumulative time in C#?

I want to calculate the time span between 2 times which I saved in a database.
So literally I want to know the length of time between the 2 values.
14:10:20 - 10:05:15 = 02:05:05
So the result would be 02:05:05.
How would I be able to achieve this using C#?
14:10:20 is the format I saved it in in my database.
Read the two time values into TimeSpan variables, then perform a .Subtract() on the bigger TimeSpan variable to get the TimeSpan result.
E.g. TimeSpan difference = t1.Subtract(t2);.
Your first step will be to get the timevalues stored in your database into .NET DateTime structs.
If you stored them as SQL-DateTime values in the database you can get them directly as DateTime. It would look something like this:
SQLCommand getTimeCommand = new SQLCommand("SELECT time FROM table", dbConnection);
SQLDataReader myReader = getTimeCommand.ExecuteReader();
while (myReader.Read())
{
DateTime time = myReader.GetDateTime(0);
}
myReader.Close();
Your implementation might differ, refer to the ADO.NET documentation in the MSDN library.
If you already got a string representing the time you can parse the string into a DateTime using the static methods
DateTime.Parse
or
DateTime.ParseExact
In your case you might need to use ParseExact, which can pe provided with a format-string defining how to read the string. Examples should be found in the MSDN library.
Durations in .NET are stored inside a TimeSpan struct. Getting the elapsed time between to datetimes is easy:
DateTime time1, time2; //filled with your timevalues from the db
TimeSpan elapsed = d2 - d1;
elapsed now contains the timespan between the two DateTimes. There are several members for the struct to access the TimeSpan. Look into the MSDN-Library to find the ones you need.
DateTime objects support the "-" operator so you can just read your times into such objects and subtract them. To test, check this out:
DateTime then = DateTime.Now;
Thread.Sleep(500);
DateTime now = DateTime.Now;
TimeSpan time = now - then;
MessageBox.Show(time.ToString());

Categories