Convert DateTime format to Matlab Date Serial Number format - c#

I want to be able to convert the DateTime (2012/12/31 10-21-17.617) to a decimal number that Matlab takes (Date Serial Number).
I have converted the Matlab date serial number to the Datetime format (yyy/mm/dd HH:mm:ss.fff) by using this:
DateTime conv = new DateTime(1, 1, 1).AddDays(734139.045000000040).AddYears(-1)
However i would like to be able to do the opposite of the above. I know the .NET date starts from 0001/01/01 where as for Matlab it is 0000/00/00.

Unless I'm missing something, a simple approach would be TimeSpan.TotalDays (http://msdn.microsoft.com/en-us/library/system.timespan.totaldays.aspx)
Create a timespan from an arbitrary point to the DateTime you're trying to convert, then adjust as necessary with the offset to get it into matlab format.
Added code example
private DateTime MatlabToNET(double days)
{
return new DateTime(1, 1, 1).AddDays(days).AddYears(-1);
}
private double NETtoMatlab(DateTime dt)
{
TimeSpan ts = dt - new DateTime();
return ts.TotalDays + 365;
}

Related

Why is Convert.ToDateTime() not working in this example?

I'm trying to use both System.DateTime.Now.ToString() and Convert.ToDateTime and was running into some strange behavior. I have narrowed down the problem to the Convert.ToDateTime. For some reason a DateTime type set with System.DateTime.Now is not the same as one that has been converted from a string. However when you output either of them they appear to be the same.
(I have tried using Trim(), TrimStart(), and TrimEnd() to no avail.)
This is the output in console after running this in unity:
http://imgur.com/1ZIdPH4
using UnityEngine;
using System;
public class DateTimeTest : MonoBehaviour {
void Start () {
//Save current time as a DateTime type
DateTime saveTime = System.DateTime.Now;
//Save above DateTime as a string
string store = saveTime.ToString();
//Convert it back to a DateTime type
DateTime convertedTime = Convert.ToDateTime(store);
//Output both DateTimes
Debug.Log(saveTime + "\n" + convertedTime);
//Output whether or not they match.
if (saveTime == convertedTime)
Debug.Log("Match: Yes");
else
Debug.Log("Match: No");
//Output both DateTimes converted to binary.
Debug.Log(saveTime.ToBinary() + "\n" + (convertedTime.ToBinary()));
}
}
You lose a lot when you convert a DateTime to a string via DateTime.ToString().
Even if you include the milliseconds like this:
DateTime convertedTime =
new DateTime(
saveTime.Year,
saveTime.Month,
saveTime.Day,
saveTime.Hour,
saveTime.Minute,
saveTime.Second,
saveTime.Millisecond);
you would still get a different DateTime that is not equal to the original one.
The reason for this is that internally a DateTime stores a number of ticks (since 12:00:00 midnight, January 1, 0001). Each tick represents one ten-millionth of a second. You need to get the same number of Ticks for the two DateTime objects to be equal.
So, to get an equal DateTime, you need to do this:
DateTime convertedTime = new DateTime(saveTime.Ticks);
Or if you want to convert it to a string (to store it), you can store the ticks as a string like this:
string store = saveTime.Ticks.ToString();
DateTime convertedTime = new DateTime(Convert.ToInt64(store));
The result of DateTime.ToString() does not include milliseconds. When you convert it back to DateTime, you basically truncate the milliseconds, so it returns a different value.
For example
var dateWithMilliseconds = new DateTime(2016, 1, 4, 1, 0, 0, 100);
int beforeConversion = dateWithMilliseconds.Millisecond; // 100
var dateAsString = dateWithMilliseconds.ToString(); // 04-01-16 1:00:00 AM (or similar, depends on culture)
var dateFromString = Convert.ToDateTime(dateAsString);
int afterConversion = dateFromString.Millisecond; // 0
I think you are losing your time zone during the ToString() method. So the re-converted DateTime ends up in a different time zone.
Check also the DateTime.Kind property.

Converting DateTime to unix timestamp and back again - result is not equal

I recently started learning C# and ran into a bug, I tracked it down and discovered it was because if I convert a DateTime object to a timestamp, then back to a DateTime object, the resulting DateTime doesn't equal the original one, even though to me they seem identical.
I put together a snippet to exhibit what I mean
void Main()
{
DateTime ePoch = new DateTime(1970, 1, 1, 0, 0, 0);
DateTime dateTime = DateTime.UtcNow;
TimeSpan timeSpan = (dateTime.ToUniversalTime() - ePoch);
double unixTimeStamp = timeSpan.TotalSeconds;
DateTime dateTimeConvertedBack = ePoch.AddSeconds(unixTimeStamp);
System.Console.WriteLine(dateTime);
System.Console.WriteLine(dateTimeConvertedBack);
System.Console.WriteLine(dateTime.Millisecond);
System.Console.WriteLine(dateTimeConvertedBack.Millisecond);
System.Console.WriteLine(dateTime == dateTimeConvertedBack); //results in false??
}
Which prints:
12/08/2013 15:43:56
12/08/2013 15:43:56
977
977
False
Why aren't these two objects treated as equal?
I'm pretty certain an == test on DateTime should compare values and not the refs.
They aren't the same. Look at dateTime.Ticks and dateTimeConvertedBack.Ticks.
This will work:
DateTime dateTimeConvertedBack = ePoch.AddTicks(timeSpan.Ticks);

DateTime to duration conversion

Does c# have support for converting two DateTime's to the xs:duration data type? (I'm assuming I need two DateTime values for this?)
References: http://www.w3.org/TR/xmlschema-2/#duration and http://www.w3schools.com/schema/schema_dtypes_date.asp (half way down)
There was support for this in the XMLConvert class as explained here: http://kennethxu.blogspot.de/2008/09/xmlserializer-doesn-serialize-timespan.html
I ended up using this code and it displays the value in the xml correct
[XmlElementAttribute("ValidThrough", DataType = "duration")]
[DataMember(Name = "ValidThrough")]
[DefaultValue("P10D")]
public string ValidThrough
{
get
{
return XmlConvert.ToString(_validThroughField);
}
set
{
_validThroughField= XmlConvert.ToTimeSpan(value);
}
}
[XmlIgnore]
public TimeSpan _validThroughField { get; set; }
TimeSpan is what you are looking for.
A TimeSpan object represents a time interval (duration of time or
elapsed time) that is measured as a positive or negative number of
days, hours, minutes, seconds, and fractions of a second. The TimeSpan
structure can also be used to represent the time of day, but only if
the time is unrelated to a particular date. Otherwise, the DateTime or
DateTimeOffset structure should be used instead.
Example:
DateTime dt1 = new DateTime(2012, 10, 2, 10, 20, 00);
DateTime dt2 = DateTime.Now;
TimeSpan ts = dt1 - dt2;

Convert formatted date string to DateTime(int,int,int,int,int,int) to pass into a function

I am comparing the time now to a time stored somewhere in a database. The time stored in the database is in the format of "yyyyMMddHHmmss". For example, the database may return 201106203354 for a stored time value. I am then using a function to compare the time now to the time read in from the database.
What I am doing now:
Create 6 int variables
Take the sub-string from the formatted date string and convert the sub-string to an int32.
Pass the 6 int variables to the function.
What I would like to do:
Rather than splitting up the formatted date-time string, and seperately creating and assigning six variables to pass to the function, I would like to know if there is some way to simply convert the formatted date-time string into DateTime.
Please see my code as it will help to explain what I clearly cannot ...
Pass time now along with time read from database:
Private void passTime()
{
string timeStamp;
int year, month, day, hour, minutes, seconds;
DateTime dt = DateTime.Now;
timeStamp = dt.ToString("yyyyMMddHHmmss");
year = Convert.ToInt32(timeStamp.Substring(0, 4));
month = Convert.ToInt32(timeStamp.Substring(4, 2));
day = Convert.ToInt32(timeStamp.Substring(6, 2));
hour = Convert.ToInt32(timeStamp.Substring(8, 2));
minutes = Convert.ToInt32(timeStamp.Substring(10, 2));
seconds = Convert.ToInt32(timeStamp.Substring(12, 2));
MessageBox.Show(GetDifferenceDate(
new DateTime(year,month,day,hour,minutes,seconds),
// Example time from database
new DateTime(2011, 08, 11, 11, 40, 26)));
}
static string GetDifferenceDate(DateTime date1, DateTime date2)
{
if (DateTime.Compare(date1, date2) >= 0)
{
TimeSpan ts = date1.Subtract(date2);
return string.Format("{0} days",
ts.Days);
}
else
return "Not valid";
}
So, quite simply, I would like to compare two dates that are both in the format of "yyyyMMddHHmmss", or if this is not possible, I would like to convert the previous Date string into a DateTime.
I'm sure I left something out here, I will go back and read it again but please feel free to ask me anything that I left unclear.
Thank you,
Evan
You're looking for ParseExact:
DateTime.ParseExact(timeStamp, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)

How to convert javascript numeric date into C# date (using C#, not javascript!)

I'm scraping a website and in the html it has a date in the following format:
"date":"\/Date(1184050800000-0700)\/"
If this was in javascript, it would be a date object and I could use its methods to retrieve the data in whatever format I like. However, I'm scraping it in a C# app. Does anyone know what this format is? Is it the total number of seconds after a certain date or something? I need a way to convert this to a C# datetime object.
If I'm not mistaken, that is a Unix timestamp in milliseconds. 1184050800000 is the timestamp itself, and -0700 is the time zone. This epoch convertor confirms.
Here is some code I've used before for converting Unix timestamps into DateTimes. Be sure to include only the part before -0700:
/// <summary>
/// Converts a Unix timestamp into a System.DateTime
/// </summary>
/// <param name="timestamp">The Unix timestamp in milliseconds to convert, as a double</param>
/// <returns>DateTime obtained through conversion</returns>
public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp / 1000); // convert from milliseconds to seconds
}
If you encounter Unix timestamps that are in seconds, you just have to remove the / 1000 part of the last line of the code.
As sinelaw says it seems to be a regex of some sort, however I tried parsing out the numeric values:
1184050800000-0700
And they seem to correspond to:
1184050800000 - Unix timestamp in milliseconds
-0700 - this would be the timezone offset UTC-07:00
You could parse it (I assume it's a string from a JSON object) and convert it to a DateTime like this:
string dateString = "/Date(1184050800000-0700)/";
Regex re = new Regex(#"(\d+)([-+]\d{4})");
Match match = re.Match(dateString);
long timestamp = Convert.ToInt64(match.Groups[1].Value);
int offset = Convert.ToInt32(match.Groups[2].Value) / 100;
DateTime date = new DateTime(1970, 1, 1).AddMilliseconds(timestamp).AddHours(-offset);
Console.WriteLine(date); // 7/10/2007 2:00:00 PM
Am I wrong? It looks like a regexp to me, not a date object at all.
DateTime now = new DateTime(1184050800000);
Console.WriteLine(now); // 2/01/0001 8:53:25 AM
Could this be correct if you aren't interested in the year?

Categories