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!
Related
I'm developing a WebAPI. Where I have an Entity called Assignment. Assignment has a property called DateScheduled which is a long, that represents a UnixTimeStamp in milliseconds. Now on creation of an Assignment, I have a method called BeginningOfDay(long date) which looks like this
public static long BeginningOfDay(long date)
{
DateTimeOffset beg = DateTime.SpecifyKind(DateTimeOffset.FromUnixTimeMilliseconds(date).Date, DateTimeKind.Utc);
return beg.ToUnixTimeMilliseconds();
}
If the user passes in 02-10-2021 21:01:00 the method will give me 02-10-2021 00:00:00.
Now the date that the user passes in is already in Utc. But when calling beg.ToUnixTimeMilliseconds() it's converting it to UTC once again. Which is leading to a lot of problems? I hope you guys understand my issue. When running it locally it's working fine. But on the server, it's messing up because of where it's located at. Given parameter 1633903199 it's returning 1633816800 locally which is correct. But the same parameter on azure is giving 1633824000 which is incorrect.
Instead of .Date use UtcDateTime so all your code will be aligned with UTC dates.
The code will be like this:
DateTimeOffset.FromUnixTimeMilliseconds(date).UtcDateTime
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"));
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.
I have an application that reads 'timed' data out of a file; currently, my input is something like this:
-- EDIT -- I have found an actual case where this fails.
0:0:1:934 > >> GOOD MORNING.<br>
But I seem to be having some trouble parsing this into a valid TimeSpan.
I would appreciate if someone could point me in the right direction, as not many offerings that I've found thus far provided much in the way of solving the problem.
As my code stands;
String StoredTime = ArchiveLine.Split('>')[0].TrimEnd();
String StoredFrame = ArchiveLine.Substring(ArchiveLine.IndexOf('>')+1).TrimStart();
TimeSpan FrameTime = TimeSpan.Parse(StoredTime, DateTimeFormatInfo.InvariantInfo);
And it throws a format exception.
Thanks.
It may be a localisation issue. Some cultures use a comma instead of a period as the decimal point. Try:
TimeSpan FrameTime = TimeSpan.Parse(StoredTime, DateTimeFormatInfo.InvariantInfo);
The problem here is that (I) referenced the wrong portion of my line in the Parse method...
I have the following C# that is giving me the error above when trying to parse string to datetime.
DateTime backupdate = System.Convert.ToDateTime(imageflowlabel.Text);
DateTime currentdate = System.DateTime.Now.AddHours(-2);
int result = currentdate.CompareTo(backupdate);
imageflowlable.text looks like this 2012-04-15 15:23:34:123
Any ideas on how to convert this?
Thanks
Yes - use "DateTime.ParseExact()" or "TryParseExact()" with a custom format string:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
DateTime currentdate;
int result;
try
{
// EXAMPLE: 2012-04-15 15:23:34:123
DateTime backupdate =
DateTime.ParseExact (
"yyyy-MM-dd HH:mm:ss:fff", //mind the casing
imageflowlabel.Text,
CultureInfo.InvariantCulture);
currentdate = System.DateTime.Now.AddHours(-2);
result = currentdate.CompareTo(backupdate);
}
catch (Exception ex)
{
...
Your problem is with the time part of your dateTime string. If your string read "2012-04-15 15:23:34.123" then it would work. You could modify your string and replace the last colon with a period and that would fix it.
Your code looks correct; the issue is presumably with your string format, whose last : should actually be a . (indicating the start of the fractional seconds).
Incorrect: 2012-04-15 15:23:34:123
Correct: 2012-04-15 15:23:34.123
Convert.ToDateTime("2012-04-15 15:23:34.123") works fine.
ParseExact should work for you, assuming your users have no way of editing that value on their own; in that case, you should use TryParseExact to unless you want the FormatException.
var toParse = "2012-04-15 15:23:34:123";
var parsed = DateTime.ParseExact(toParse, "yyyy-MM-dd HH:mm:ss:fff", null);
Assert.AreEqual(new DateTime(2012, 4, 15, 15, 23, 34, 123), parsed);
I have seen several answers to resolve the situation outlined in this question such as using DateTime.Parse, DateTime.ParseExact, or Convert.ToDateTime. I am trying to determine why the problem is seemlingly inconsistent. I built an application using the Microsoft Enterprise Library Software Factory with a SQL Server 2008 R2 backend and it has been in production for about 9 months now. It has at least 20 instances with the same code format that assign DateTime property values from C# to System.Data.DBType.DateTime parameters for stored procedures. 19 of the 20 code blocks work fine. For the 20th I had to add the .ToString() call as shown below to resolve the error mentioned in this question.
db.AddInParameter(command, "beginDT", DbType.DateTime, timeBlock.BeginDT.ToString());
So anyone have some insight on why would it work fine in 19 absolutely identical instances and not in the 20th? I am just trying to get more of an understanding of the inter-relationship of these objects so I can build solid code. I have since gone back to all other instances and added the .ToString() call. Haven't completed my regression testing though; so, I don't know if that was a mistake.