How can I convert ticks to a date format? - c#

I am converting a ticks value to a date like this:
Convert(datetime, (MachineGroups.TimeAdded - 599266080000000000)/864000000000);
Using this i get:
9/27/2009 10:50:27 PM
But I want just the date in this format:
October 1, 2009
My sample ticks value is
633896886277130000
What is the best way to do this?

A DateTime object can be constructed with a specific value of ticks. Once you have determined the ticks value, you can do the following:
DateTime myDate = new DateTime(numberOfTicks);
String test = myDate.ToString("MMMM dd, yyyy");

It's much simpler to do this:
DateTime dt = new DateTime(633896886277130000);
Which gives
dt.ToString() ==> "9/27/2009 10:50:27 PM"
You can format this any way you want by using dt.ToString(MyFormat). Refer to this reference for format strings. "MMMM dd, yyyy" works for what you specified in the question.
Not sure where you get October 1.

private void button1_Click(object sender, EventArgs e)
{
long myTicks = 633896886277130000;
DateTime dtime = new DateTime(myTicks);
MessageBox.Show(dtime.ToString("MMMM d, yyyy"));
}
Gives
September 27, 2009
Is that what you need?
I don't see how that format is necessarily easy to work with in SQL queries, though.

Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.
public class Time
{
public static void Timestamps()
{
OutputTimestamp();
Thread.Sleep(1000);
OutputTimestamp();
}
private static void OutputTimestamp()
{
var timestamp = DateTime.UtcNow.Ticks;
var localTicks = DateTime.Now.Ticks;
var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
Console.Out.WriteLine("Timestamp = {0}. Local ticks = {1}. Local time = {2}.", timestamp, localTicks, localTime);
}
}
Output:
Timestamp = 636988286338754530. Local ticks = 636988034338754530. Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736. Local ticks = 636988034348878736. Local time = 2019-07-15 4:03:54 PM.

Related

Conversion to Unix timestamp is not working

I'm trying to convert DateTime to Unix timestamp.
static long ToUnixTime(DateTime dateTime)
{
var dateTimeOffset = new DateTimeOffset(dateTime);
return dateTimeOffset.ToUnixTimeSeconds();
}
But this function always return timestamp equal to something "Sun Jan 18 1970" instead of current DateTime. What is wrong with this?
The current date as expressed as a Unix timestamp is 1501093539, more or less.
I think you're checking yourself wrong; if I edit my code to add milliseconds, I get 1/18/1970. But unix times aren't in milliseconds. They're in seconds.
var dt = DateTime.Now;
var offset = new DateTimeOffset(dt);
var unix = offset.ToUnixTimeSeconds();
dt = new DateTime(1970,1,1,0,0,0);
dt = dt.AddSeconds(unix);
Debug.WriteLine(dt); // gives current date back
Change it to AddSeconds and you'll get the current date. Change it to AddMilliseconds and you'll get January 18th, 1970. Your code is actually fine.
Here is some code that will give you Unix time stamp with any version of the framework
public static class UnixDateTime
{
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
public static long GetUnixTimestamp(this DateTime input)
{
return (long)(input - UnixEpoch).TotalSeconds;
}
}
Then just use the extension method
var unixTimeStamp = DateTime.Now.GetUnixTimestamp();

How to convert the "time" from DateTime into int?

I have a DataGrid which contains a few values that are in hours and I wanted to know:
How to get ONLY the time from my DataGrid and convert it into an int (or double) variable.
My goal is to do a few operations with my DataGrid time values, like to add numbers into it
EXAMPLE:
Using my "dataGridView1.Rows[1].Cells[2].Value.ToString();" It'll show a DateTime value (which is inside my DataGrid), with this value, I wanna filter ONLY the time from this and convert it into an int
the part of my code which I wanna "capture" the time:
txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value.ToString();
string value = dataGridView1.Rows[0].Cells[2].Value.ToString();
lblLeft.Text = value.Split(' ')[1];
I wanna get the "value" (which is a DateTime value from the DataGrid) and convert it into an int.
note:
- The date for me in my dataGrid it's not relevant, I only have to pick the time (and yes, I know that I can't "split" DateTime to do them separately)
If you are willing to be limited to millisecond resolution, then this is fairly easy.
Given a date/time that you want to get the time part from as an int, you can get the number of milliseconds since midnight, like so:
DateTime dateTime = DateTime.Now;
int timeMsSinceMidnight = (int)dateTime.TimeOfDay.TotalMilliseconds;
If you want to reconstitute the original date and time from this, you need the original date and the time since midnight in milliseconds:
DateTime date = dateTime.Date; // Midnight.
DateTime restoredTime = date.AddMilliseconds(timeMsSinceMidnight);
Test program:
DateTime dateTime = DateTime.Now;
Console.WriteLine("Original date/time: " + dateTime );
int timeMsSinceMidnight = (int)dateTime.TimeOfDay.TotalMilliseconds;
DateTime date = dateTime.Date; // Midnight.
DateTime restoredTime = date.AddMilliseconds(timeMsSinceMidnight);
Console.WriteLine("Restored date/time: " + restoredTime);
The value returned from time.TimeOfDay is of type TimeSpan, which is convenient for storing time-of-day values.
If you want to turn your "milliseconds since midnight" back into a TimeSpan, you just do this:
var timeSpan = TimeSpan.FromMilliseconds(timeMsSinceMidnight);
First step is to convert string to DateTime. Use DateTime.TryParse(string value, out DateTime dt). Then as Mathew Watson rightly suggested, get the value of variable dt converted to milliseconds using dt.TimeOfDay.TotalMilliseconds. It is also possible to convert the span in TotalSeconds or TotalMinutes if it suits your requirement.
Try to avoid calling ToString() method directly before checking if cell value is null. If I want to avoid the check, I would make compiler to do it by using something like : Rows[3].Cells[2].Value + "" instead of Value.ToString().
Mixing Mathew's and Mukesh Adhvaryu's answers, I got into this one, and it fits perfectly on what I need, thank you guys for your support!
txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value + "";
string value = dataGridView1.Rows[0].Cells[2].Value + "";
lblLeft.Text = value.Split(' ')[1];
textStatus.Text = "";
DateTime timeConvert;
DateTime.TryParse(value, out timeConvert);
double time;
time = timeConvert.TimeOfDay.TotalMilliseconds;
var timeSpan = TimeSpan.FromMilliseconds(time);
lblSoma.Text = timeSpan.ToString();
static void Main(string[] args)
{
string time1 = "11:15 AM";
string time2 = "11:15 PM";
var t1 = ConvertTimeToInt(time1);
var t2 = ConvertTimeToInt(time2);
Console.WriteLine("{0}", t1);
Console.WriteLine("{0}", t2);
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", ConvertIntToTime(t1));
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", ConvertIntToTime(t2));
Console.ReadLine();
}
static long ConvertTimeToInt(string input)
{
var date = DateTime.ParseExact(input, "hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan span = date.TimeOfDay;
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", date);
return span.Ticks;
}
static DateTime ConvertIntToTime(long input)
{
TimeSpan span = TimeSpan.FromTicks(input);
var date = new DateTime(span.Ticks);
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", date);
return date;
}

How can I setup DateTime hour,minute and second?

private void StartAuction()
{
DateTime closeDate;
closeDate = DateTime.Parse(Console.ReadLine());
}
I am able to set the date,month and year but I want the hours,minutes and seconds to setup automatically to the current time of the day. for example if the current time is 15:24, I want the user to add the date which could be 21/03/2013 and then I want the time to be 15:24:00 and not 00:00:00 as it currently does.
Any suggestions?
Well you can use DateTime.Now to get the current time, then take the TimeOfDay from that and add it to the Date of your existing DateTime:
private void StartAuction()
{
DateTime closeDate = DateTime.Parse(Console.ReadLine());
DateTime closeDateAtCurrentTime = closeDate.Date + DateTime.Now.TimeOfDay;
...
}
(I'm explicitly using the Date property so that even if the user does enter a time as well, it's basically stripped.)
As a blatant plug, you might also want to consider using my Noda Time library, which separates out the ideas of "date", "time" and "date/time" into different types. (As well as "local" values vs ones where you know the UTC offset or the time zone.)
var now = DateTime.Now;
var date = new DateTime(input.Year, input.Month, input.Day, now.Hour, now.Minute, now.Second);
First you need to parse with DateTime.Parse what you read from command line.
Then, you can do that using DateTime.Now.TimeOfDay like;
DateTime closeDate = DateTime.Parse(Console.ReadLine());
closeDate = closeDate.Date + DateTime.Now.TimeOfDay;
You could do
closeDate = DateTime.Parse(Console.ReadLine() + " " + DateTime.Now.TimeOfDay);
Which works, but does look a little roundabout and I wouldn't recommend it considering you're converting from a time format to a string and then back to a time format again. Lots of immutable objects being created, there.
There are other options, including to parse the date, as you do, and then add TimeOfDay to it.
DateTime closeDate;
closeDate = DateTime.Parse(Console.ReadLine());
closeDate = closeDate.Date + Date.Now.TimeOfDay;
You can do this:
closeDate = DateTime.Parse(Console.ReadLine())
.Add(DateTime.Now - DateTime.Today);
Well how about this little function:
public static DateTime ChangeTime(DateTime dateTime)
{
return new DateTime(
dateTime.Year,
dateTime.Month,
dateTime.Day,
DateTime.Now.Hour,
DateTime.Now.Minute,
DateTime.Now.Second,
DateTime.Now.Millisecond,
DateTime.Now.Kind);
}
This is a possible solution:
store DateTime.Now in a variable
var date = DateTime.Now;
Then u can access the Hours, Minutes and Seconds like this:
date.Hour;
date.Minute;
date.Second;

Date difference returning wrong answer

I would really like some guidance on this problem i have been facing.
I am trying to find out the difference between 2 dates from textbox.
protected void Button1_Click(object sender, EventArgs e)
{
a = TextBox1.Text.ToString().Trim();
b = TextBox2.Text.ToString().Trim();
DateTime c = new DateTime();
DateTime d = new DateTime();
c = Convert.ToDateTime(a);
d = Convert.ToDateTime(b);
System.TimeSpan diffr = d - c;
Response.Write(diffr.Days);
}
The above is the code i have written on Button Click event.
The problem is that, the code returns the difference wrong.
i.e if the diff between 12/02/2013 and 11/02/2013 is to be found, instead of returning 1
the code returns 30.
Similarly diff between 12/02/2013 and 10/02/2013 is to be found, instead of returning 2
the code returns 61.
I am using the Jquery DatePicker for selecting the date!
Kindly help as all my search has not yielded any solutions.
You should convert your date format to dd/mm/yyyy before doing substraction.
So here is your final code-
protected void Button1_Click(object sender, EventArgs e)
{
string a, b;
a = TextBox1.Text.ToString().Trim();
b = TextBox2.Text.ToString().Trim();
DateTime c = new DateTime();
DateTime d = new DateTime();
c = Convert.ToDateTime(a);
d = Convert.ToDateTime(b);
DateTime to_datetime = DateTime.ParseExact(a, "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
DateTime from_datetime = DateTime.ParseExact(b, "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
System.TimeSpan diffr = to_datetime - from_datetime;
Response.Write(diffr.Days);
}
The only problem is the format of the date.
As you have written it is showing the month difference rather than date difference.
Try using datetime.parseexact and specify your format
Example:-
string poop = "2005-12-14T14:35:32.1700000-07:00";
DateTime poo = DateTime.ParseExact(poop,"yyyy-MM-ddTHH:mm:ss.fffffffzzz",
System.Globalization.CultureInfo.InvariantCulture);
In your case
string sDate1=TextBox1.Text.ToString().Trim();
string sDate2=TextBox1.Text.ToString().Trim();
DateTime dt1= DateTime.ParseExact(sDate1,"MM-dd-yyyy",
System.Globalization.CultureInfo.InvariantCulture);
DateTime dt2= DateTime.ParseExact(sDate2,"MM-dd-yyyy",
System.Globalization.CultureInfo.InvariantCulture);
System.TimeSpan diffr =dt2 - dt1;
Response.Write(diffr.Days);
And it should work.
You can change the jQuery datepicker's date format as
$("#txtDate.datepicker").datepicker({ dateFormat: 'mm-dd-yy' });
In jQuery, you can parse the test to date as
var dateInJs = $.datepicker.parseDate('mm-dd-yy', $('#txtDate.datepicker').val());
Or in .NET you can parse the date in 'dd-MM-yyyy' format as
DateTime.ParseExact(txtDate.Text, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
also you can use CultureInfo in .NET like
DateTime Date = DateTime.Parse(txtDate.Text, System.Globalization.CultureInfo.CreateSpecificCulture("hi-IN"));
Perhaps you can use TimeSpan:
DateTime startTime = '';
DateTime endTime = '';
TimeSpan span = endTime.Subtract( startTime );
Next you can utilize span.Seconds, span.Days...etc
I think this problem is due to your computer date time format setting. Please change your computer date time format to dd/MM/yyyy format and try again.

Check if daylight savings is in effect?

How to check if in Denmark daylight time savings has taken effect, if so, then add 1 hour to my data, else not?
I have a xml file:
<day = "1"
month = "5"
sunrise ="06:30"
sunset ="21:30"
/>
Think you need convert this xml to DateTime and then use TimeZoneInfo class.
If Denmark your local time:
DateTime thisTime = DateTime.Now;
bool isDaylight = TimeZoneInfo.Local.IsDaylightSavingTime(thisTime);
Else you need to get Denmark TimeZone:
DateTime thisTime = DateTime.Now;
// get Denmark Standard Time zone - not sure about that
TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById("Denmark Standard Time");
bool isDaylight = tst.IsDaylightSavingTime(thisTime);
When I coded as above - for New-York, I found in the debugger that the time was set correctly (including DST)
TimeZoneInfo nyTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime nyTime = GetLocalDateTime(DateTime.UtcNow, nyTimeZone);
if (nyTimeZone.IsDaylightSavingTime(nyTime))
nyTime = nyTime.AddHours(1);
public static DateTime GetLocalDateTime(DateTime utcDateTime, TimeZoneInfo timeZone)
{
utcDateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);
DateTime time = TimeZoneInfo.ConvertTime(utcDateTime, timeZone);
return time;
}
You can use TimeZoneInfo.IsDaylightSavingTime
DateTime theDate = new DateTime(2012, 5, 1); // may 1st
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
bool isCurrentlyDaylightSavings = tzi.IsDaylightSavingTime(theDate);
Here is a generic test and happy to be corrected if my math is incorrect. In my case I just needed to get the GMT offset for the timezone regardless of where it was in the world.
int timezone;
TimeZoneInfo localZone = TimeZoneInfo.Local;
DateTime myTime = DateTime.Now;
bool isDayLight = TimeZoneInfo.Local.IsDaylightSavingTime(myTime);
if (isDayLight)
timezone = Math.Abs(localZone.BaseUtcOffset.Hours) + 1;
else
timezone = Math.Abs(localZone.BaseUtcOffset.Hours);
Debug.WriteLine("timezone is " + timezone);
I simply found the current time and if it was in Day Light Savings period added +1 to the GMT offset.
This works with Visual Studio Express 2013.
You need to do two things:
call IsAmbiguous
List item IsDaylightSavingTime.
if (TimeZoneInfo.Local.IsAmbiguousTime(unclearDate) ||
TimeZoneInfo.Local.IsDaylightSavingTime(unclearDate))
Console.WriteLine("{0} may be daylight saving time in {1}.", unclearDate, TimeZoneInfo.Local.DisplayName);
https://msdn.microsoft.com/en-us/library/bb460642(v=vs.110).aspx
this is my short solution which can be using in all timezones:
DateTime utcTime = DateTime.Parse("30.10.2018 18:21:34")
DateTime localtime = ConvertUTCToLocalTime(utcTime);
public static DateTime ConvertUTCToLocalTime(DateTime UTCTime)
{
var localZone = TimeZone.CurrentTimeZone;
var offset = localZone.GetUtcOffset(UTCTime);
var localTime = UTCTime.AddHours(offset.Hours);
return localTime;
}
Important
myDateTime.IsDaylightSavingTime DOES return the proper value... but... it is accurate down to at least the hour of the day, just passing the date alone isn't enough.
For instance this year (2019) 3/10/2019 02:00:00 passed as myDateTime will return false, but 3/10/2019 03:00:00 will return true.
Based on other codes provided above, I made a complete code to run and make tests. The variable cityTz is receiving an IANA timezone name example. IANA timezone pattern is used in Mac and Linux (Windows uses different timezone style). In 2020, daylight-saving (DST) in New York ends on November 01. If you test the code below, the return will be FALSE, because "theDate" is November 02, the next day after the end of DST. But if you change the line commented and set theDate to November 01 (last DST date in NY), the return will be TRUE.
You can compile this program in Mac or Linux terminal typing:
csc testDST.cs
To run your program:
mono testDST.exe
Complete code:
using System;
using System.Collections.Generic;
using System.Linq;
class Program{
static void Main(string[] args)
{
string cityTz;
//cityTz = "America/Sao_Paulo";
cityTz = "America/New_York";
//DateTime theDate = new DateTime(2020, 11, 1); //returns TRUE
DateTime theDate = new DateTime(2020, 11, 2); //returns FALSE
Console.WriteLine("Data: "+theDate);
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(cityTz);
bool isDaylight = tzi.IsDaylightSavingTime(theDate);
Console.WriteLine("isDaylight this date in "+ cityTz +"?: "+ isDaylight);
}
}

Categories