Remove Seconds from DateTime c# - 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>

Related

time of change and convert to datetime

I have to select changelists from perforce the problem is when I extracted information but the problem is that the date and the time look not significative so how can I change this string to significative date and time
example of result 1361898522
the code:
P4Command cm1 = new P4Command(ps, "changes", true, String.Format("{0}", deppath1));
Options opchanges = new Options();
opchanges.Add(op1,op2);
P4CommandResult results1 = cm1.Run(opchanges);
TaggedObjectList listfiledown1 = new TaggedObjectList();
listfiledown1 = (results1.TaggedOutput);
foreach (TaggedObject obj in listfiledown1)
{
foreach (String s in obj.Keys)
{
String value = "n/a";
obj.TryGetValue(s, out value);
var changeList = value.Split ('#');
}
}
If the value 1361898522 is meant to be Tue, 26 Feb 2013 17:08:42 UTC, then it looks like this is a Unix timestamp - a number of seconds since the Unix epoch. This is easy to do in C#:
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0,
DateTimeKind.Utc);
...
public static DateTime FromUnixTimestamp(long seconds)
{
return UnixEpoch + TimeSpan.FromSeconds(seconds);
}
Note the UTC DateTimeKind so that the epoch is appropriately UTC rather than in the system local time zone.
Using my Noda Time project it's even easier, as of version 1.1:
Instant timestamp = Instant.FromSecondsSinceUnixEpoch(seconds);
I suspect that the date time values are expressed in Unix time: the number of seconds since January 1, 1970.
For example, if you write:
var epoc = new DateTime(1970, 01, 01);
dt = epoc + TimeSpan.FromSeconds(1361898522);
Console.WriteLine(dt);
The result is:
2013/02/26 17:08:42

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

C#: Unix timestamp and DateTime

we are developing a C# web application that has to deal with Unix timestamps and C# DateTime objects. A timestamp has to be converted into a DateTime object.
The following example shows my problem: The DateTime should be '18.10.2011 14:02:32'
System.DateTime time = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
time = time.AddSeconds(1318939352);
System.Console.Out.WriteLine("Time: " + time); // -> 18.10.2011 12:02:32
If I call ToLocalTime() on my developer machine, the DateTime is correct:
System.DateTime time = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
time = time.AddSeconds(1318939352).ToLocalTime();
System.Console.Out.WriteLine("Time: " + time); // -> 18.10.2011 14:02:32
But the application will run on servers which are hosted in another timezone (GMT Standard Time), so I have to deal with a different time zone and the second example fails on this servers.
Independent of where I host the application, the date in this case should always be printed as 18.10.2011 14:02:32.
Does anyone know how I can do this? Thanks in advance!
Best Regards,
Thorsten
You can have a look TimeZoneInfo
public struct DateTimeWithZone
{
private readonly DateTime utcDateTime;
private readonly TimeZoneInfo timeZone;
public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
{
utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTime, timeZone);
this.timeZone = timeZone;
}
public DateTime UniversalTime
{
get { return utcDateTime; }
}
public TimeZoneInfo TimeZone
{
get { return timeZone; }
}
public DateTime LocalTime
{
get { return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); }
}
}

reverse this function

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);
}

How to get the start and end times of a day

In my C# app, I pass a string variable that is of format yyyymmdd-yyyymmdd that represents a from and to date. I want to get the start and end times for these dates respectively. Currently I have the below code but was wondering if there was more of an elegant solution?
So for pdr = 20090521-20090523 would get "20090521 00:00:00" and "20090523 23:59:59"
private void ValidateDatePeriod(string pdr, out DateTime startDate,
out DateTime endDate)
{
string[] dates = pdr.Split('-');
if (dates.Length != 2)
{
throw new Exception("Date period is of incorrect format");
}
if (dates[0].Length != 8 || dates[1].Length != 8)
{
throw new Exception("Split date periods are of incorrect format");
}
startDate = DateTime.ParseExact(dates[0] + " 00:00:00",
"yyyyMMdd HH:mm:ss", null);
endDate = DateTime.ParseExact(dates[1] + "23:59:59",
"yyyyMMdd HH::mm:ss", null);
}
I am surprised to see how an incorrect answer received so many upvotes:
The correct version would be as follows:
public static DateTime StartOfDay(this DateTime theDate)
{
return theDate.Date;
}
public static DateTime EndOfDay(this DateTime theDate)
{
return theDate.Date.AddDays(1).AddTicks(-1);
}
You could define two extension methods somewhere, in a utility class like so :
public static DateTime EndOfDay(this DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 23, 59, 59, 999);
}
public static DateTime StartOfDay(this DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0, 0);
}
And then use them in code like so :
public DoSomething()
{
DateTime endOfThisDay = DateTime.Now.EndOfDay();
}
If you are only worried about .Net precision...
startDate = DateTime.ParseExact(dates[0], "yyyyMMdd");
endDate = DateTime.ParseExact(dates[1], "yyyyMMdd").AddTicks(-1).AddDays(1);
You really don't need to concatenate extra values onto the string for the time portion.
As an addendum, if you are using this for a query against, for example, a database...
startDate = DateTime.ParseExact(dates[0], "yyyyMMdd");
endDate = DateTime.ParseExact(dates[1], "yyyyMMdd").AddDays(1);
With a query of...
WHERE "startDate" >= #startDate AND "endDate" < #endDate
Then the precision issues noted in the comments won't really matter. The endDate in this case would not be part of the range, but the outside boundary.
The DateTime object has a property called Date which will return just the date portion. (The time portion is defaulted to 12:00 am).
I would recommend as a more elegant solution (IMHO) that if you want to allow any datetime on the last day, then you add 1 day to the date, and compare to allow times greater than or equal to the start date, but strictly less than the end date (plus 1 day).
// Calling code. beginDateTime and endDateTime are already set.
// beginDateTime and endDateTime are inclusive.
// targetDateTime is the date you want to check.
beginDateTime = beginDateTime.Date;
endDateTime = endDateTime.Date.AddDays(1);
if ( beginDateTime <= targetDateTime &&
targetDateTime < endDateTime )
// Do something.
public static class DateTimeExtension {
public static DateTime StartOfTheDay(this DateTime d) => new DateTime(d.Year, d.Month, d.Day, 0, 0,0);
public static DateTime EndOfTheDay(this DateTime d) => new DateTime(d.Year, d.Month, d.Day, 23, 59,59);
}
I use the following in C#
public static DateTime GetStartOfDay(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0, 0);
}
public static DateTime GetEndOfDay(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 23, 59, 59, 999);
}
Then in MS SQL I do the following:
if datepart(ms, #dateEnd) = 0
set #dateEnd = dateadd(ms, -3, #dateEnd)
This will result in MS SQL time of 23:59:59.997 which is the max time before becoming the next day.
You could simply use:
new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 23, 59, 59, 999);
Which will work in MS SQL, but this is not as accurate in .Net side.
That's pretty much what I would do, with some small tweaks (really no big deal, just nitpicking):
The TryParse()/TryParseExact() methods should be used which return false instead of throwing exceptions.
FormatException is more specific than Exception
No need to check for Length == 8, because ParseExact()/TryParseExact() will do this
"00:00:00" and "23:59:59" are not needed
return true/false is you were able to parse, instead of throwing an exception (remember to check value returned from this method!)
Code:
private bool ValidateDatePeriod(string pdr, out DateTime startDate,
out DateTime endDate)
{
string[] dates = pdr.Split('-');
if (dates.Length != 2)
{
return false;
}
// no need to check for Length == 8 because the following will do it anyway
// no need for "00:00:00" or "23:59:59" either, I prefer AddDays(1)
if(!DateTime.TryParseExact(dates[0], "yyyyMMdd", null, DateTimeStyles.None, out startDate))
return false;
if(!DateTime.TryParseExact(dates[1], "yyyyMMdd", null, DateTimeStyles.None, out endDate))
return false;
endDate = endDate.AddDays(1);
return true;
}
I think we're doing it wrong. There is no such thing as the end of the day. AddTick(-1) only works under the convention that there are no time intervals smaller than a tick. Which is implementation dependent. Admittedly the question comes with a reference implementation, namely the .Net Framework DateTime class, but still we should take this as a clue that the function we really want is not EndOfDay() but StartOfNextDay()
public static DateTime StartOfNextDay(this DateTime date)
{
return date.Date.AddDays(1);
}
The issue above regarding the few milliseconds can be resolved by querying the database with the next day's start date.
For example:
SELECT * FROM temp WHERE createdDate >= fromDate AND createdDate < toDate
Using the extension methods below you could set the from and to dates to:
DateTimeOffset fromDate = DateTimeOffset.UtcNow.StartOfDay();
DateTimeOffset toDate = DateTimeOffset.UtcNow.EndOfDay();
public static class DateExtentions
{
public static DateTimeOffset StartOfDay(this DateTimeOffset dateTime)
{
return new DateTimeOffset(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0, 0, dateTime.Offset);
}
public static DateTimeOffset EndOfDay(this DateTimeOffset dateTime)
{
return dateTime.StartOfDay().AddDays(1);
}
public static DateTimeOffset StartOfMonth(this DateTimeOffset dateTime)
{
return new DateTimeOffset(dateTime.Year, dateTime.Month, 1, 0, 0, 0, 0, dateTime.Offset);
}
public static DateTimeOffset EndOfMonth(this DateTimeOffset dateTime)
{
return dateTime.StartOfMonth().AddMonths(1);
}
public static DateTimeOffset StartOfYear(this DateTimeOffset dateTime)
{
return new DateTimeOffset(dateTime.Year, 1, 1, 0, 0, 0, 0, dateTime.Offset);
}
public static DateTimeOffset EndOfYear(this DateTimeOffset dateTime)
{
return dateTime.StartOfYear().AddYears(1);
}
}
For SQL Server (version 2008 R2 tested) this ranges works.
StarDate '2016-01-11 00:00:01.990'
EndDate '2016-01-19 23:59:59.990'
Seems like ticks is greater that the last second of day and automatically round to next day. So i test and works, i made a dummy table with two dates for check what values is sql server catching and inserting in the stored procedure those parameters.
In Java 8, you can do it using LocalDate as follows:
LocalDate localDateStart = LocalDate.now();
Date startDate = Date.from(localDateStart.atStartOfDay(ZoneId.systemDefault()).toInstant());
LocalDate localDateEnd = localDateStart.plusDays(1);
Date endDate = Date.from(localDateEnd.atStartOfDay(ZoneId.systemDefault()).toInstant());

Categories