Datetime.now as TimeSpan value? - c#

I need the current Datetime minus myDate1 in seconds.
DateTime myDate1 = new DateTime(1970, 1, 9, 0, 0, 00);
DateTime myDate2 = DateTime.Now;
TimeSpan myDateResult = new TimeSpan();
myDateResult = myDate2 - myDate1;
.
.
I tried different ways to calculate but to no effect.
TimeSpan mySpan = new TimeSpan(myDate2.Day, myDate2.Hour, myDate2.Minute, myDate2.Second);
.
The way it's calculated doesn't matter, the output should just be the difference these to values in seconds.

Code:
TimeSpan myDateResult = DateTime.Now.TimeOfDay;

Your code is correct. You have the time difference as a TimeSpan value, so you only need to use the TotalSeconds property to get it as seconds:
DateTime myDate1 = new DateTime(1970, 1, 9, 0, 0, 00);
DateTime myDate2 = DateTime.Now;
TimeSpan myDateResult;
myDateResult = myDate2 - myDate1;
double seconds = myDateResult.TotalSeconds;

Have you tried something like
DateTime.Now.Subtract(new DateTime(1970, 1, 9, 0, 0, 00)).TotalSeconds
DateTime.Subtract Method (DateTime)
TimeSpan.TotalSeconds Property

How about
myDateResult.TotalSeconds
http://msdn.microsoft.com/en-us/library/system.timespan.totalseconds

you need to get .TotalSeconds property of your timespan :
DateTime myDate1 = new DateTime(2012, 8, 13, 0, 05, 00);
DateTime myDate2 = DateTime.Now;
TimeSpan myDateResult = new TimeSpan();
myDateResult = myDate2 - myDate1;
MessageBox.Show(myDateResult.TotalSeconds.ToString());

You can use Subtract method:
DateTime myDate1 = new DateTime(1970, 1, 9, 0, 0, 00);
DateTime myDate2 = DateTime.Now;
TimeSpan ts = myDate2.Subtract(myDate1);
MessageBox.Show(ts.TotalSeconds.ToString());

TimeSpan myDateResult;
myDateResult = DateTime.Now.Subtract(new DateTime(1970,1,9,0,0,00));
myDateResult.TotalSeconds.ToString();

Related

convert 1+year midnight time into unix milliseconds

i am trying to convert current year + 1 midnight date time to unix timestamp.
for that i have tried
DateTime currentTime = DateTime.Today;
DateTime yearEnd = new DateTime( currentTime.Year, 1,1,currentTime.Minute,currentTime.Hour,currentTime.Second,DateTimeKind.Local);
yearEnd = yearEnd.AddYears(1);
double t = (yearEnd.ToUniversalTime() - new DateTime(1970, 1, 1,0,0,0)).TotalMilliseconds;
and above code is returning 1514782800000 i.e. Mon Jan 01 2018 05:00:00 UTC in and Mon Jan 01 2018 10:30:00 Local (india)
what i am expecting is it converts time to Mon Jan 01 2018 00:00:00 local time
By default DateTime creates Unspecified DateTimeKind, so using UTC explicitly helps to avoid confusion. I've tried to rewrite in this way
DateTime currentTime = DateTime.UtcNow;
DateTime yearEnd = new DateTime( currentTime.Year, 1,1,0,0,0, DateTimeKind.Utc);
yearEnd = yearEnd.AddYears(1); // output DateTime has Utc Kind
var unixTimestamp = (yearEnd.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalMilliseconds;
Console.WriteLine(unixTimestamp);
The output is 1514764800000 which converts to GMT: Monday, 1 January 2018 00:00:00
Update:
In case you need to convert timestamp back to DateTime you may use the following:
public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp);
return dtDateTime; // still Utc Kind
}
Usage example if you need to convert to other timezone:
TimeZoneInfo infotime = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time (Mexico)"); // specify your desired timezone here
Console.WriteLine(TimeZoneInfo.ConvertTimeFromUtc(UnixTimeStampToDateTime(unixTimestamp), infotime));
if i understand you right you want the following:
double result = new DateTime(currentTime.Year + 1, 1, 1, 0, 0, 0, DateTimeKind.Local).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
Or improved for readablity
DateTime newYear = new DateTime(currentTime.Year + 1, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime uTSBegin = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
double result2 = newYear.Subtract(uTSBegin).TotalSeconds;

how convert unix timestamp to datetime

I'm trying to convert this unix timestamp
1415115303410
in DateTime, in this way:
private static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
{
System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp);
return dtDateTime;
}
But I get a wrong date:
Date: {04/11/0045 00:00:00}
NOTE: dtDateTime.AddSeconds(unixTimeStamp) throws an exception.. my number is in Milliseconds.
with this online conversion tool http://www.epochconverter.com/ I get the right conversion:
04/11/2014 15:35:03 GMT+0:00
How I can convert this one?
Your code is working just fine, as is. Here is a fiddle.
Everyone that is telling you to use AddSeconds is wrong. The number you are giving us is clearly in milliseconds. There are 31,536,000 seconds in a year. 1415115303410 divided by 31536000 is 4487. There hasn't been 4,487 years passed since 1/1/1970.
use AddSeconds instead of AddMilliseconds
private static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
{
System.DateTime dtDateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);
return dtDateTime;
}
Just use DateTimeOffset
DateTimeOffset date = DateTimeOffset.FromUnixTimeSeconds(1415115303410)
public DateTime FromUnixTime(long unixTime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddMilliseconds(unixTime);
}
var date = FromUnixTime(1415115303410); // 11/4/2014 3:35:03 PM
Since your number is in milliseconds, Unix time, use AddMilliseconds.
Try This
DateTime date = new DateTime(Convert.ToInt64("1415115303410"));
Microsoft continue thinking about us! All solutions to add seconds/milliseconds is not working with Visual Studio 2017 (.Net 4.6.1). But there is a new solution:
public static DateTime numStrToDate(String val)
{
DateTime dRet = new DateTime(1970, 1, 1, 0, 0, 0, 0);
long dSec;
if (long.TryParse(val, out dSec))
{
TimeSpan ts = new TimeSpan(dSec*10l);
dRet = dRet.Add(ts);
}
return dRet;
}
If you need a UTC time - just add 'System.DateTimeKind.Utc' to the DateTime constructor call.
Date to Timestamp
DateTime date = DateTime.ParseExact(date_string, "dd/MM/yyyy H:mm:ss", null);
Double timestamp = Math.Truncate((date.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
Timestamp to Date
DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Unspecified);
dtDateTime = dtDateTime.AddSeconds(Double.Parse(arrayFinalResponse[i, 5])).ToLocalTime();
String date = dtDateTime.ToString("dd/MM/yyyy H:mm:ss", CultureInfo.GetCultureInfo("en-US"));
You can do the conversion by using a little trick with date command.
It does depend on your timezone. I live in UTC + 1 so for me it is like this:
h1x1binax:~ # date -d "Thu Jan 1 01:00:00 CET 1970 + 1415115303410 second"
Thu Mar 21 09:16:50 CET 46813
h1x1binax:~ #
So that's not a unixtime timestamp ... it is probably in milliseconds so need to divide by 1000
h1x1binax:~ # date -d "Thu Jan 1 01:00:00 CET 1970 + 1415115303 second"
Tue Nov 4 16:35:03 CET 2014
h1x1binax:~ #

How to work with DateTime.Now to ticks [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to add the phones current time to my date time list. I need it to be able to subtract with the ticks. I have tried using phonecurrentime.ToString("dd hh:mm"); but because it's a string there are no ticks and all sorts of errors!
I need it to work with DateTime.now.
Here is my code:
InitializeComponent();
List<DateTime> theDates = new List<DateTime>();
DateTime fileDate, closestDate;
theDates.Add(new DateTime(2000, 1, 1, 10, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
// This is the date that should be found
theDates.Add(new DateTime(2000, 1, 1, 4, 22, 0));
// This is the date you want to find the closest one to
fileDate = DateTime.Now;
long min = long.MaxValue;
foreach (DateTime date in theDates)
{
if (Math.Abs(date.Ticks - fileDate.Ticks) < min)
{
min = Math.Abs(date.Ticks - fileDate.Ticks);
closestDate = date;
}
}
Darren Davies above is correct.
You can add/subtract datetime objects. The result is of type TimeSpan, which lets you easily compare date and/or time differences.
Also, you should give a name to each date you add to your list (assign to a variable then add to list). A month later you won't remember what each day meant ;)
if you have a string and want to convert it to DateTime you can use
CultureInfo cf = new CultureInfo("en-us");
if(DateTime.TryParseExact("12 12:45", "dd hh:mm", cf, DateTimeStyles.None, out fileDate))
{
// your code
}
and your code would look like:
List<DateTime> theDates = new List<DateTime>();
DateTime fileDate, closestDate;
theDates.Add(new DateTime(2000, 1, 1, 10, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
// This is the date that should be found
theDates.Add(new DateTime(2000, 1, 1, 4, 22, 0));
CultureInfo cf = new CultureInfo("en-us");
string timeToParse = phonecurrentime.ToString("dd hh:mm");
if(DateTime.TryParseExact(timeToParse, "dd hh:mm", cf, DateTimeStyles.None, out fileDate))
{
long min = long.MaxValue;
foreach (DateTime date in theDates)
{
if (Math.Abs(date.Ticks - fileDate.Ticks) < min)
{
min = Math.Abs(date.Ticks - fileDate.Ticks);
closestDate = date;
}
}
}
if you want to compare the time part of the dateTime you can use TimeOfDay property:
TimeSpan ts = DateTime.Now.TimeOfDay;
foreach (DateTime date in theDates)
{
long diff = Math.Abs(ts.Ticks - date.TimeOfDay.Ticks);
if (diff < min)
{
min = diff;
closestDate = date;
}
}
fileDate = phonecurrentime.ToString("dd hh:mm");
Will not compile. fileDate is a DateTime object. You need to assign it to another DateTime object, not a string.
If phonecurrenttime is a DateTime you can ommit the .ToString() method.
fileDate = phonecurrenttime;
Edit
From your comment, if you simply want to assign the current ddate/time to fileDate you can use DateTime.Now:
fileDate = DateTime.Now;

How to convert Long type datetime to DateTime with correct time zone

For example 1297380023295 should be 2010/2/11 9 AM
I use this code right now
long dateNumber = num;
long beginTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
DateTime dateValue = new DateTime(beginTicks + dateNumber * 10000);
return dateValue;
The result of this function is 1 AM,It is GMT.
What can I do with it?
You're looking for the ToLocalTime() method:
long unixDate = 1297380023295;
DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime date= start.AddMilliseconds(unixDate).ToLocalTime();
long a= 634792557112051692;
//a= ticks time
DateTime dt = new DateTime(a);
Response.Write(dt.Hour.ToString());
//dt.hour convert time ticks to time hour
You can specify the DateTimeKind when you create a new DateTime object, so you could specify that as UTC and then use .ToLocalTime to convert it to local time:
long dateNumber = 1297380023295;
long beginTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
DateTime dt = new DateTime(beginTicks + dateNumber * 10000, DateTimeKind.Utc);
MessageBox.Show(dt.ToLocalTime().ToString());
U can use static methods from DateTimeOffset.
DateTimeOffset.FromUnixTimeSeconds()
DateTimeOffset.FromUnixTimeMilliseconds()
Depends in wich format you have your ticks.
and if u want DateTime you can use for example
var ticks = 1635091250;
var dateTime = DateTimeOffset.FromUnixTimeSeconds(ticks).DateTime;
Powershell script piece, just FYI
$minDate = New-Object "System.DateTime"
$minDate = $minDate.AddYears(1969)
$minDate.AddMilliseconds(1446616420947)

C# seconds since specific date

In C# 3.0, how do I get the seconds since 1/1/2010?
Goes like this:
TimeSpan test = DateTime.Now - new DateTime(2010, 01, 01);
MessageBox.Show(test.TotalSeconds.ToString());
For one liner fun:
MessageBox.Show((DateTime.Now - new DateTime(2010, 01, 01))
.TotalSeconds.ToString());
You can substract 2 DateTime instances and get a TimeSpan:
DateTime date = new DateTime(2010,1,1);
TimeSpan diff = DateTime.Now - date;
double seconds = diff.TotalSeconds;
Just to avoid timezone issues
TimeSpan t = (DateTime.UtcNow - new DateTime(2010, 1, 1));
int timestamp = (int) t.TotalSeconds;
Console.WriteLine (timestamp);
It's really a matter of whose 2010-Jan-01 you're using and whether or not you wish to account for daylight savings.
//I'm currently in Central Daylight Time (Houston, Texas)
DateTime jan1 = new DateTime(2010, 1, 1);
//days since Jan1 + time since midnight
TimeSpan differenceWithDaylightSavings = DateTime.Now - jan1;
//one hour less than above (we "skipped" those 60 minutes about a month ago)
TimeSpan differenceWithoutDaylightSavings = (DateTime.UtcNow - jan1.ToUniversalTime());
//difference for those using UTC and 2010-Jan-01 12:00:00 AM UTC as their starting point
// (today it's 5 hours longer than differenceWithDaylightSavings)
TimeSpan utcDifference = (DateTime.UtcNow - new DateTime(2010, 1, 1));
Difference with Daylight Savings: 105.15:44:09.7003571
Difference without Daylight Savings: 105.14:44:09.7003571
UTC Difference: 105.20:44:09.7003571
To get the seconds, use the TotalSeconds property off the TimeSpan object.
protected void Page_Load(object sender, EventArgs e)
{
SecondsSinceNow(new DateTime(2010, 1, 1, 0, 0, 0));
}
private double SecondsSinceNow(DateTime compareDate)
{
System.TimeSpan timeDifference = DateTime.Now.Subtract(compareDate);
return timeDifference.TotalSeconds;
}
DateTime t1 = DateTime.Now;
DateTime p = new DateTime(2010, 1, 1);
TimeSpan d = t1 - p;
long s = (long)d.TotalSeconds;
MessageBox.Show(s.ToString());

Categories