reverse this function - c#

i have code that takes a csharp datetime and converts it into a long to plot in the "flot" graph. here is the code
public static long GetJavascriptTimestamp(DateTime input)
{
TimeSpan span = new TimeSpan(DateTime.Parse("1/1/1970").Ticks);
DateTime time = input.Subtract(span);
return (long)(time.Ticks / 10000);
}
I now need an opposite function where i take this long value and get the csharp datetime object back. any idea if the above method can be reversed ?

DateTime date = new DateTime(1970, 1, 1).Add(new TimeSpan(yourLong * 10000));

Aren't you just looking for this?
public static DateTime DateTimeFromJavascript(long millisecs)
{
return new DateTime(1970, 1, 1).AddMilliseconds(millisecs);
}

Can be:
public static DateTime GetTimestampFromJS(long ts)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(ts*1000);
}

Related

Remove Seconds from DateTime c#

I have a section of code that converts the unix timestamp value to a standard time, however it is returning hours, minutes, and seconds. I would like it to only return Hours and Minutes.
convertSunriseTime = UnixTimeStampToDateTime(currentSunriseTime).ToString();
convertSunsetTime = UnixTimeStampToDateTime(currentSunsetTime).ToString();
private static TimeSpan UnixTimeStampToDateTime(long unixTimeStamp)
{
DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);
return dtDateTime.TimeOfDay;
}
and the moment the varibles convertSunriseTime and convertSunsetTime come back with seconds.
So you want to format your value to show hours and minutes. You can do this:
convertSunriseTime = UnixTimeStampToDateTime(currentSunriseTime).ToString("hh\\:mm");
Here, the parameter to the ToString() method specifies that you are only interested in getting the hours and minutes parts into the resulting string. This is called a custom TimeSpan format string. There is also a set of standard ones: Standard TimeSpan format strings
this can do the work:
private static TimeSpan UnixTimeStampToDateTime(long unixTimeStamp)
{
DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);
dtDateTime = DateTime.FromMinutes((int)dtdateTime.TotalMinutes);
return dtDateTime.TimeOfDay;
}
Can you try this way
convertSunriseTime = UnixTimeStampToDateTime(currentSunriseTime).ToString();
convertSunsetTime = UnixTimeStampToDateTime(currentSunsetTime).ToString();
<pre>private static TimeSpan UnixTimeStampToDateTime(long unixTimeStamp) </pre>
<pre>{</pre>
<pre>DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);</pre>
<pre>dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);</pre>
<pre>return dtDateTime.TimeOfDay;</pre>
<pre>}</pre>

Convert Eorzea DateTime value to Earth time

A while ago I posted the following, which was gladly answered by olitee (all credit goes to him for the solution):
Convert DateTime value to Final Fantasy XIV Eorzea Game Time
I was trying to add features to my code and one would require to be able to put that Eorzea time (FFXIV) back to Earth time for alerts.
The following code, provided by olitee, was converting Earth time to Eorzea time just fine:
public static class EorzeaDateTimeExtention
{
public static DateTime ToEorzeaTime(this DateTime date)
{
const double EORZEA_MULTIPLIER = 3600D/175D;
long epochTicks = date.ToUniversalTime().Ticks - (new DateTime(1970, 1, 1).Ticks);
long eorzeaTicks = (long)Math.Round(epochTicks * EORZEA_MULTIPLIER);
return new DateTime(eorzeaTicks);
}
}
How would I achieve the opposite? I tried to revert the mathematical calculations but apparently it keeps giving me negative epochTicks which results in error whenever I try the conversion.
Apparently I am missing something or I got it wrong at some point.
My understanding of the ticks is quite limited.
Any help and/or tips would be greatly appreciated.
Thanks a lot in advance.
The ToEarthTime method should give you the earth time.
class Program
{
static void Main(string[] args)
{
var now = DateTime.Now;
var ff = now.ToEorzeaTime();
Console.WriteLine($"Now: {now} | FF: {ff}");
var ffNew = new DateTime(ff.Ticks, DateTimeKind.Utc);
var nowNew = ffNew.ToEarthTime();
Console.WriteLine($"Now: {nowNew} | FF: {ffNew}");
Console.ReadLine();
}
}
public static class Converter
{
private const double EORZEA_MULTIPLIER = 3600D / 175D;
public static DateTime ToEorzeaTime(this DateTime date)
{
long epochTicks = date.ToUniversalTime().Ticks - (new DateTime(1970, 1, 1).Ticks);
long eorzeaTicks = (long)Math.Round(epochTicks * EORZEA_MULTIPLIER);
return new DateTime(eorzeaTicks);
}
public static DateTime ToEarthTime(this DateTime date)
{
var epochTicks = (long) Math.Round(date.Ticks/EORZEA_MULTIPLIER);
var earthTicks = epochTicks + new DateTime(1970, 1, 1).Ticks;
var utc = new DateTime(earthTicks, DateTimeKind.Utc);
return utc.ToLocalTime();
}
}

Convert DateTime to Int

This is the sample I did in SQL Server
SELECT CAST(CAST('2012-01-25 10:00:00.000' AS DATETIME) AS INT) + 2
Result is 40933
How can I achieve this using c#? From where and how this integer comes?
Reference: Convert from DateTime to INT but this is what I need in c#
I don't understand why you would need to represent a DateTime as an integer in C#, but you can use this method:
public static int DateTimeToInt(DateTime theDate)
{
return (int)(theDate.Date - new DateTime(1900, 1, 1)).TotalDays + 2;
}
And you can use this method for the reverse operation:
public static DateTime IntToDateTime(int intDate)
{
return new DateTime(1900, 1, 1).AddDays(intDate - 2);
}
extension to cast dateTime to timestamp
public static int DateTimeToInt(this DateTime theDate)
{
int unixTime = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
return unixTime;
}
better to cast dateTime to long, use property DateTime.Ticks for this

how to convert from millisecond to DateTime in c#

private static DateTime FromMS(long microSec)
{
long milliSec = (long)(microSec / 1000);
DateTime startTime = new DateTime(1970, 1, 1);
TimeSpan time = TimeSpan.FromMilliseconds(milliSec);
DateTime v = new DateTime(time.Ticks);
DateTime result = new DateTime(startTime.Year + v.Year, startTime.Month + v.Month, startTime.Day + v.Day, startTime.Hour + v.Hour, startTime.Minute + v.Minute, startTime.Millisecond + v.Millisecond);
return result;
}
This result is wrong...
Why ???
You already have the result of the conversion to milliseconds when you do:
TimeSpan time = TimeSpan.FromMilliseconds(milliSec);
DateTime v = new DateTime(time.Ticks); //This is the result
If you want to add the milliseconds to UNIX time, then all you have to do is:
TimeSpan time = TimeSpan.FromMilliseconds(milliSec);
DateTime result = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
result = result.Add(time);
If the time isn't in UTC then omit the DateTimeKind.Utc part, but it's generally a good idea to keep the time in UTC and only convert to local time when needed.
private static DateTime FromMS(long microSec)
{
long milliSec = (long)(microSec / 1000);
DateTime startTime = new DateTime(1970, 1, 1);
TimeSpan time = TimeSpan.FromMilliseconds(milliSec);
return startTime.Add(time);
}
I use this method to convert from a Unix Epoch (with milliseconds) to a DateTime object
private static readonly DateTime UnixEpochStart =
DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
public static DateTime ToDateTimeFromEpoch(this long epochTime)
{
DateTime result = UnixEpochStart.AddMilliseconds(epochTime);
return result;
}
long ticks = new DateTime(1970, 1, 1).Ticks;
DateTime dt = new DateTime(ticks);
dt.AddMilliseconds(milliSec);
Try this.
TimeSpan time = TimeSpan.FromMilliseconds(1509359657633);
DateTime date = new DateTime(1970, 1, 1).AddTicks(time.Ticks);
This will convert milliseconds into a correct DateTime.
NOTE:- If you get the milliseconds from JS like Date.now() the millisecond you received here is for UTC. So when you convert to C# DateTime, you will get DateTime in UTC time

How to convert Milliseconds to date format in C#?

In C# how can I convert Unix-style timestamp to yyyy-MM-ddThh:mm:ssZ?
Start by converting your milliseconds to a TimeSpan:
var time = TimeSpan.FromMilliseconds(milliseconds);
Now, in .NET 4 you can call .ToString() with a format string argument. See http://msdn.microsoft.com/en-us/library/system.timespan.tostring.aspx
In previous versions of .NET, you'll have to manually construct the formatted string from the TimeSpan's properties.
new DateTime(numTicks * 10000)
The DateTime(long ticks) constructor is what you need. Each tick represents 100 nanoseconds so multiply by 10000 to get to 1 millisecond.
If the milliseconds is based on UNIX epoch time, then you can use:
var posixTime = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
var time = posixTime.AddMilliseconds(milliSecs);
This worked for me:
DateTimeOffset.FromUnixTimeMilliseconds(milliseconds);
You can get just the DateTime from that if you need it.
Here you go:
public static class UnixDateTime
{
public static DateTimeOffset FromUnixTimeSeconds(long seconds)
{
if (seconds < -62135596800L || seconds > 253402300799L)
throw new ArgumentOutOfRangeException("seconds", seconds, "");
return new DateTimeOffset(seconds * 10000000L + 621355968000000000L, TimeSpan.Zero);
}
public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)
{
if (milliseconds < -62135596800000L || milliseconds > 253402300799999L)
throw new ArgumentOutOfRangeException("milliseconds", milliseconds, "");
return new DateTimeOffset(milliseconds * 10000L + 621355968000000000L, TimeSpan.Zero);
}
public static long ToUnixTimeSeconds(this DateTimeOffset utcDateTime)
{
return utcDateTime.Ticks / 10000000L - 62135596800L;
}
public static long ToUnixTimeMilliseconds(this DateTimeOffset utcDateTime)
{
return utcDateTime.Ticks / 10000L - 62135596800000L;
}
[Test]
public void UnixSeconds()
{
DateTime utcNow = DateTime.UtcNow;
DateTimeOffset utcNowOffset = new DateTimeOffset(utcNow);
long unixTimestampInSeconds = utcNowOffset.ToUnixTimeSeconds();
DateTimeOffset utcNowOffsetTest = UnixDateTime.FromUnixTimeSeconds(unixTimestampInSeconds);
Assert.AreEqual(utcNowOffset.Year, utcNowOffsetTest.Year);
Assert.AreEqual(utcNowOffset.Month, utcNowOffsetTest.Month);
Assert.AreEqual(utcNowOffset.Date, utcNowOffsetTest.Date);
Assert.AreEqual(utcNowOffset.Hour, utcNowOffsetTest.Hour);
Assert.AreEqual(utcNowOffset.Minute, utcNowOffsetTest.Minute);
Assert.AreEqual(utcNowOffset.Second, utcNowOffsetTest.Second);
}
[Test]
public void UnixMilliseconds()
{
DateTime utcNow = DateTime.UtcNow;
DateTimeOffset utcNowOffset = new DateTimeOffset(utcNow);
long unixTimestampInMilliseconds = utcNowOffset.ToUnixTimeMilliseconds();
DateTimeOffset utcNowOffsetTest = UnixDateTime.FromUnixTimeMilliseconds(unixTimestampInMilliseconds);
Assert.AreEqual(utcNowOffset.Year, utcNowOffsetTest.Year);
Assert.AreEqual(utcNowOffset.Month, utcNowOffsetTest.Month);
Assert.AreEqual(utcNowOffset.Date, utcNowOffsetTest.Date);
Assert.AreEqual(utcNowOffset.Hour, utcNowOffsetTest.Hour);
Assert.AreEqual(utcNowOffset.Minute, utcNowOffsetTest.Minute);
Assert.AreEqual(utcNowOffset.Second, utcNowOffsetTest.Second);
Assert.AreEqual(utcNowOffset.Millisecond, utcNowOffsetTest.Millisecond);
}
}
This sample will demonstrate the general idea, but you need to know if your starting date is DateTime.MinValue or something else:
int ms = 1000; // One second
var date = new DateTime(ms * 10000); // The constructor takes number of 100-nanoseconds ticks since DateTime.MinValue (midnight, january 1st, year 1)
string formatted = date.ToString("yyyy-MM-ddTHH:mm:ssZ");
Console.WriteLine(formatted);
You can construct your datetime from ticks:
long ticks = new DateTime(1979, 07, 28, 22, 35, 5,
new CultureInfo("en-US", false).Calendar).Ticks;
DateTime dt3 = new DateTime(ticks);
Console.Write(dt3.ToString("yyyy-MM-ddThh:mm:ssZ"));
private static DateTime Milliseconds2Date(Double d)
{
TimeSpan time = TimeSpan.FromMilliseconds(d);
return new DateTime(1970, 1, 1) + time;
}
private static Double Date2Milliseconds(DateTime d)
{
var t = d.Subtract(new DateTime(1970, 1, 1));
return t.TotalMilliseconds;
}
This question should have the answer you need.
Short version:
DateTime date = new DateTime(long.Parse(ticks));
date.ToString("yyyy-MM-ddThh:mm:ssZ");

Categories