C# compare time and date in unity - c#

hy am trying to compare current date and trying to perform action when specific date comes. but it doesn't work in c# unity.
here is code:
string over = "2017/06/28 22:38:30";
string dateAndTimeVar = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
if (dateAndTimeVar == over)
{
print(dateAndTimeVar);
}

I believe that the main problem you are having is using the "==" operator.
Since you are wanting it to be equal down to the second, you are relying on Unity to run your piece of code every second. If this is not the case, then your code may be missed when the time comes.
Since you are using strings you are stuck with this option. You could instead use DateTime objects to perform the comparison.
var over = DateTime.Parse("2019/04/01 17:09:10");
var dateAndTimeVar = System.DateTime.Now;
if (dateAndTimeVar >= over)
{
print(dateAndTimeVar);
}

string dateInput = "2017/06/28 22:38:30";
DateTime parsedDate = DateTime.Parse(dateInput);
if (DateTime.Now > parsedDate)
{
print("It is Over");
}
You Can Parser to a DateTime, And Compare that.

When I had common problem, I used DateTime.Now to get current time.
For comparring DateTime objects, it's easy to use DateTime.Ticks property.
As I understood from your code, you want to execute print(dateAndTimeVar);, when comes the time.
It's better to compare, like:
if(DateTime.Now.Ticks >= dateTimeOver)
{
print(dateAndTimeVar);
}

System.DateTime.Now, in its most basic form, uses the clock of the computer running the program. Since you're including seconds in your datetimes, for the conditional to evaluate to true you would have to evaluate it at the exact second specified in the string 'over'. Going from only the posted code it would be highly unlikely that you'd be able to run the program and evaluate the conditional at the exact second specified without something else to control the environment. A simple way to debug this would be to print out the variables or use a debugger to actually see what the computer is seeing at the time of execution.

Related

How to extract date from datetime in C# without converting it into string?

I am trying to extract date from date time field but in C# it is not helping me to do it without converting it to string.
This is my class:
public class Student_Info
{
public String Student_Name;
public DateTime DateofBirth;
}
Student_Info student = new Student_Info();
student.Student_Name = "XYZ";
student.DateofBirth = Convert.ToDateTime("2019-01-01");
MessageBox.Show(student.Student_Name + "" + student.DateofBirth);
This is how I am setting the value.
My expected result is XYZ 2019-01-01
But I am getting XYZ 1/1/2019 12:00:00 AM
Need Help?
Thanks in Advance
The DateTime struct always has a time component. There is a Date property that will mostly do what you asked, but even that has an implied time of midnight.
However, while the question text says this:
without converting it into string?
the code sample IS implicitly converting to a string:
MessageBox.Show(student.Student_Name + "" + student.DateofBirth);
In which case there are a number of options:
student.DateofBirth.ToShortDateString()
student.DateofBirth.ToString("d")
student.DateofBirth.ToString("d", CultureInfo.CreateSpecificCulture("de-DE")) //German format. You can put any culture here you need.
student.DateofBirth.ToString("d", CultureInfo.InvariantCulture)
student.DateofBrith.ToString("yyyy-MM-dd")
Just be careful here, because some of those rely on the operating system's date format, and users can configure that to do really weird stuff if they really want to.
You can also use any of these right in the MessageBox string:
MessageBox.Show($"{student.Student_Name}{student.DateofBirth:yyyy-MM-dd}");
MessageBox.Show(string.Format(CultureInfo.InvariantCulture, "{0}{1:d}", student.Student_Name, student.DateofBirth));
Finally, I get a little scared whenever I see someone wanting to create a date string resembling the ISO-8601 date format, as is the case here. There are plenty of legitimate reasons to do this. However, there is one common reason people want to do this that also happens to be very bad: SQL. If you're doing this so you can include it in an SQL command string, you're almost certainly doing something very wrong, and you need to take a step back and research parameterized queries before doing anything else.
Try this
MessageBox.Show(student.Student_Name + "" + student.DateofBirth.ToString("yyyy-MM-dd"));

Create a recurring event at midnight using C#, Unity Game Engine

In a game, I want to trigger an event every night at midnight. The following code is not working:
void Update()
{
var tomorrow = DateTime.Now.AddDays(1).ToShortDateString();
var today = DateTime.Now.ToShortDateString();
if (tomorrow == today)
{
THE THING I WANT TO HAPPEN AT MIDNIGHT;
}
}
In debugging I have found that THE THING I WANT TO HAPPEN works fine. However, the event isn't triggering from the if statement.
I searched the archives for answers, and found some, but the solutions aren't working - this is almost certainly a simple error due to my extremely low-level programming knowledge.
Any assistance would be great...Thanks!
Your code is effectively asking "1 == 1 + 1?" and the answer will always be no.
You need to keep the last execution date stored outside the method, and you also need to be more careful how you do your comparison. For instance, DateTime.Now == DateTime.Now might return false (and pretty often), because DateTime stores the time down to the tick, and if it's off by even one tick, it won't be considered equal.
Try this:
DateTime lastExecutionDate = DateTime.Utc;
void Update()
{
var tomorrow = DateTime.Now.AddDays(1).ToShortDateString();
var now = DateTime.Utc;
if (lastExecutionDate.Day < now.Day)
{
lastExecutionDate = now;
// this code will be called as close to midnight as unity allows.
}
}
I'm not sure if it will be considered midnight immediately when the game starts. If it is, try using this for lastExecutionDate instead...
DateTime lastExecutionDate = DateTime.UtcNow + TimeSpan.FromDays(1);
if (tomorrow == today) this will never be true. If it is exactly midnight (Jan 01 2000 12:00:00.0000) then this line: tomorrow = DateTime.Now.AddDays(1) will equal midnight...tomorrow, all the time (Jan 02 2000 12:00:00.0000). The same applies to every other date-time.
You're better off checking to see if the current time is midnight, then store the current date somewhere and DoTheThing() only if it's currently midnight and the stored date is not today's date.
Of course, this also ignores the issue of "do you want the event to be triggered retroactively if the application is not actively run at midnight." In which case, TimeSpans and Last_run_date may be of interest.

Subtraction using DateTime retrieved from database giving strange results

I am having some trouble doing some DateTime subtractions with a time that I have received from a MySQL database. All of the non-UTC times are in the American format.
This is the time I have received (I retrieve it from the database using a Ruby on Rails app), which comes in the form of a string:
2017-04-10T15:00:00.000Z
I then parse the string to convert it to a DateTime and do a debug of the regular DateTime (without the offset):
start_time = DateTimeOffset.Parse(event_time[2]);
Debug.Log(start_time.DateTime);
Which then shows the following:
4/10/2017 3:00:00 PM
This appears similar to the format I usually use (i.e. M/dd/yyy h/mm/ss tt), so I do a quick comparison with the current time to check exactly how far off I am from it (for reference, DateTime.Now = 4/10/2017 12:46:26 AM when I ran this code last):
TimeSpan tmp;
tmp = (start_time.DateTime).Subtract(DateTime.Now);
Debug.Log(tmp)
However, this gives me the following result:
-736428.00:46:22.2744445
Doing such an operation with the following gives me a normal result:
DateTime tmp2;
TimeSpan tmp3;
tmp2 = DateTime.Now.Add(new TimeSpan(0, 0, 360));
tmp3 = tmp2.Subtract(DateTime.Now)
Debug.Log(tmp2);
Debug.Log(tmp3);
Normal Result:
4/10/2017 12:52:26 AM
00:06:00
Is there something wrong with how I have handled the time I got from my database? I can not seem to get a normal result no matter what I try.
I tried it in fiddler with the same input and syntax and I'm getting the expected result. Check how Debug.Log internally handles the TimeSpan object. Also try to print the values (difference in hour/min/seconds) before you pass it to Debug.Log to check if it reports correct result.
I found a solution to my issue (kind of?).
I also must apologize since I did not fully describe how I was using the code that I originally posted.
It turns out the issue was that I was that I was attempting to perform the DateTime subtraction in another script (I am doing this all within Unity, like I mentioned earlier).
For example, this was the code giving me the erroneous output in the script Buttonscript.cs:
TimeSpan tmpButtonController;
tmpButtonController = HighscoreController.GetComponent<HSController>().start_time.DateTime.Subtract(DateTime.Now);
Debug.Log(tmpButtonController);
But if I do the same thing, but inside the same script in which I parse the string (HSController.cs), everything is fine:
TimeSpan tmpHSController;
tmpHSController = start_time.DateTime.Subtract(DateTime.Now);
Debug.Log(tmpHSController);
Again, not exactly sure why this was was happening, but I have resolved/have a workaround for the issue now. If anyone knows why this error was occurring in the first place, please let me know!
Thank you everyone for your input!

C# 2 DateTime are not equal

I have one strange problem that I'm trying to understand.
In my controller there are 2 DateTime objects that I want to compare.
You can see screenshot from a debugger in my controller. I create one date time and get another one from a model.
At this step you can see in debugger that date1 differs from date2 for 2 seconds
At the next step I remove 2 seconds from date2 and compare it with date1
Cay you explain me why is it false? In debugger I see both of them the same.
Solution: As it was told in the comment, the idea was to check also milliseconds, I completely forgot about it!
As you can see in the reference source, a comparison of two DateTime objects is done through their respective ticks, which is their internal representation.
Comparing two DateTime values is a bit like comparing two floating point values: the difference might be so small that you're likely to not get what you want. Perhaps you need to check if they're on the same date, or if one falls in a specific range of the other.
The way to compare Datetimes is done by comparing their Tick property:
bool r = date1.Ticks == date2.Ticks;
Try this.
You can use DateTime.Compare to see which time is earlier/later. Also like people have already mentioned difference could be in e.g. milliseconds
How to use DateTime.Compare:
https://msdn.microsoft.com/en-us/library/system.datetime.compare(v=vs.110).aspx

TimeZoneInfo works differently in two bits of code

I have some code in my UI layer, which is supposed to take a DateTime, which is in UTC, and convert it to a local date time:
In my Data layer, I simply do this:
private DateTime ConvertToLocal(DateTime dt)
{
if (_currentTimeZoneUser == string.Empty)
{
var u = new UserData(_userId).GetUser(_userId);
_currentTimeZoneUser = u.TimeZoneId;
}
var reply = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt, _currentTimeZoneUser);
return reply;
}
What that does is check if _currentTimeZoneUser is set. If not, get the zimezone from the user table, and then does a conversion.
This code is working, and I get a valid result.
I then copied the code to my UI layer (As I need to do a conversion there as well, for a data grid), but 'reply' always equals 'dt'.
I googled, and noticed that I should be doing it a slightly different way. So I change my UI method to this:
public static DateTime GetLocalDateTime(DateTime serverTime)
{
var timeZoneId = HttpContext.Current.Session["TimeZoneId"].ToString();
TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
var reply = TimeZoneInfo.ConvertTimeFromUtc(serverTime, cstZone);
return reply;
}
and it works!
I can't see why it works in my data layer, but in the UI, I need to change the code.
Am I doing something wrong with my time conversion code in one of the methods?
If I'm understanding you correctly, your question boils down to the difference between ConvertTimeBySystemTimeZoneId and ConvertTimeFromUtc.
First, you need to understand that any time zone conversion operations involving DateTime may have behavioral differences depending on the value of the .Kind of DateTime you are giving it. When you look at the documentation for each of these methods (here and here), you will find a chart that describes the behavior for each of the three different kinds (Utc,Local, and Unspecified).
This is a sore point in .Net, which is why libraries like Noda Time exist. You can read more in these two articles:
What's wrong with DateTime Anyway?
The case against DateTime.Now
The actual reason for the specific problem is that you probably passed in a DateTime who's .Kind is Unspecified. In the ConvertTimeBySystemTimeZoneId method, that will be treated as if it were Local, while in the ConvertTimeFromUtc method it will be treated as if it were Utc.
There are two solutions.
The first is what you already found - use the ConvertTimeFromUtc method. You should do this in the server code also.
The second solution is to set the .Kind to Utc when you load the value from your database. Somewhere you probably have code like this:
foo.MyDateTime = (DateTime) dataReader["MyDateTime"]
Which would change to this:
foo.MyDateTime = DateTime.SpecifyKind(
(DateTime) dataReader["MyDateTime"],
DateTimeKind.Utc);
I'm assuming you are doing a direct ADO.Net call with a DataReader response. Adjust accordingly for whatever you are actually doing.

Categories

Resources