c# DateTime. Reset time to 0 - c#

I have dateTime = 3/25/2020 1:25:46 PM
Can I reset time to zero? 3/25/2020 00:00:00
Here is a demo. In this case dateTime is 3/25/2020 12:00:00 AM
class Program
{
static void Main(string[] args)
{
var datetime = DateTime.Now;
datetime = ResetTimeToStartOfDay(datetime);
Console.WriteLine(datetime);
Console.ReadLine();
}
public static DateTime ResetTimeToStartOfDay(DateTime dateTime)
{
return new DateTime(
dateTime.Year,
dateTime.Month,
dateTime.Day,
0, 0, 0, 0);
}
}
How to reset the date to the beginning of the day?

more simply:
return dateTime.Date;
But note that in the specific case of DateTime.Now you could just use DateTime.Today instead.

How to reset the date to the beginning of the day?
You already are in your method ResetTimeToStartOfDay although there is an easier way to do it with dateTime.Date which is functionally equivalent.
So your question now becomes:
Why do you see 3/25/2020 12:00:00 AM instead of 3/25/2020 00:00:00 when Console.WriteLine(datetime); is called.
When you call ToString() on the DateTime instance, which happens implicitly in Console.WriteLine(datetime);, the displayed format matches the culture of the current thread which then displays the time using AM/PM. If you want to display the date as 3/25/2020 00:00:00 then call ToString() explicitly and pass a format string like M/d/yyyy HH:mm:ss
Console.WriteLine(datetime.ToString("M/d/yyyy HH:mm:ss"));
See also Custom date and time format strings

Try:
public static DateTime SetTimeToZero(DateTime YourDate)
{
return new DateTime(YourDate.Year, YourDate.Month, YourDate.Day, 0, 0, 0);
}
or you can create an ExtensionMethod and use inside your project:
public static DateTime SetTimeToZero(this DateTime YourDate)
{
return new DateTime(YourDate.Year, YourDate.Month, YourDate.Day, 0, 0, 0);
}
How to use ExtensionMethod:
yourDatetime.SetTimeToZero(date);

Related

Convert a time in milliseconds to local date string

I am trying to convert a TimeStamp in milliseconds to a local date time. But this is weird.
The date is increased by 1 day. I don't know how stupid may I sound, but I would really be happy to have someone throw light on this.
CODE:
public static DateTime ConvertToLocalDate(string timeInMilliseconds){
double timeInTicks = double.Parse(timeInMilliseconds);
TimeSpan dateTimeSpan = TimeSpan.FromMilliseconds(timeInTicks);
DateTime dateAfterEpoch = new DateTime(1970, 1, 1) + dateTimeSpan;
DateTime dateInLocalTimeFormat = dateAfterEpoch.ToLocalTime();
return dateInLocalTimeFormat;
}
For example, if I pass:
1579631400000 which is equivalent to: 2020-01-21T18:30:00
it returns: 1/22/2020 12:00:00 AM
What is wrong?
Since your ConvertToLocalDate function returns the date and time to your local time zone. You need to convert it to UTC to get the expected date and time.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(ConvertToLocalDate("1579631400000").ToUniversalTime());
Console.ReadKey();
}
public static DateTime ConvertToLocalDate(string timeInMilliseconds)
{
double timeInTicks = double.Parse(timeInMilliseconds);
TimeSpan dateTimeSpan = TimeSpan.FromMilliseconds(timeInTicks);
DateTime dateAfterEpoch = new DateTime(1970, 1, 1) + dateTimeSpan;
DateTime dateInLocalTimeFormat = dateAfterEpoch.ToLocalTime();
return dateInLocalTimeFormat;
}
}
Or simply do not use ToLocalTime() inside your ConvertToLocalDate (if this is the case your function should not be named as ConvertToLocalDate)
Do nor use ToLocalTime().rest will work fine

How to parse datetime without date in C#?

If I have a string like 15:00 and I parse this to DateTime ot DateTimeOffset, the date is set to today.
I want somehow to distinguish, if the date part is given or not. It would help, if the date part is not given, the date is 1.1.1970.
Is there a better possibility instead of using regex and parse this by my own?
Try to parse the value as TimeSpan and then try to parse it as DateTime.
var data = "15:00";
if (TimeSpan.TryParse(data, out var time))
{
Console.WriteLine("Time: {0}", time);
}
else if (DateTime.TryParse(data, out var datetime))
{
Console.WriteLine("DateTime: {0}", datetime);
}
else
{
Console.WriteLine("I don't know how to parse {0}", data);
}
If I have a string like "15:00" and I parse this to DateTime ot
DateTimeOffset, the date is set to today.
This is by design.
From DateTime.Parse doc:
A string with a time but no date component. The method assumes the
current date unless you call the Parse(String, IFormatProvider,
DateTimeStyles) overload and include
DateTimeStyles.NoCurrentDateDefault in the styles argument, in which
case the method assumes a date of January 1, 0001.
From DateTimeOffset.Parse doc:
If is missing, its default value is the current day.
So, for DateTime, if you don't use any DateTimeStyles, you get the current date
var hours = "15:00";
var date = DateTime.Parse(hours, CultureInfo.InvariantCulture); // 12/9/2018 3:00:00 PM
but if you use DateTimeStyles.NoCurrentDateDefault as a third parameter;
var hours = "15:00";
var date = DateTime.Parse(hours, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault);
// 1/1/0001 3:00:00 PM
But I think your problem keeps on that sentence; "if the date part is given or not.." How did you decide your string has date part or not? Is it always have 5 characters as Steve commented? It can be in a format like 4:00? What about 4:1? If it can be like 4:1, it should be parsed as 4:10 or 4:01?
So, you need to decide first what is the meaning of "if the date part is given or not.." for your case. Then you can easily parse your string to TimeSpan, not DateTime in my opinion, so, you can add it created manually "1.1.1970" with DateTime(int, int, int) constructor.
if(YourConditionForYourStringNotIncludingDatePart)
{
var time = TimeSpan.Parse("15:00");
var date = new DateTime(1970, 1, 1);
var result = date.Add(time);
}
Using regular expressins for DateTime parsing is usually a bad idea. I wouldn't suggest to use it unless you have no other way to do it for DateTime.
I think for that case you could things keep simple. This could be a solution that not depends on the lenght when there is only a timepart:
void Main()
{
Console.WriteLine(ParseWithDummyIfDateAbsent("15:00", new DateTime(1970, 1, 1)));
Console.WriteLine(ParseWithDummyIfDateAbsent("15:00:22", new DateTime(1970, 1, 1)));
Console.WriteLine(ParseWithDummyIfDateAbsent("09.12.2018 15:00", new DateTime(1970, 1, 1)));
}
DateTime ParseWithDummyIfDateAbsent(string input, DateTime dummyDate)
{
if(TimeSpan.TryParse(input, out var timeSpan))
input = $"{dummyDate.Date.ToShortDateString()} {input}";
return DateTime.Parse(input);
}
Output:
01.01.1970 15:00:00
01.01.1970 15:00:22
09.12.2018 15:00:00
Depends on your localization:-)

How to get back the converted Time zone value?

I am converting a datetime value to Indian Standard Time using the below code:
public DateTime GetdatetimedetailsinIST(DateTime datetimeinfo, String timeoffsetvalue)
{
string offset= timeoffsetvalue;
string timeZoneFormat = Convert.ToString("India Standard Time");
string strIndianTimezone = timeZoneFormat;
TimeZoneInfo tzinfoIndian = TimeZoneInfo.FindSystemTimeZoneById(strIndianTimezone);
DateTime dtDateTime = datetimeinfo.AddMinutes(Convert.ToInt32(offset));//ToUniversalTime();
dtDateTime = TimeZoneInfo.ConvertTimeFromUtc(dtDateTime, tzinfoIndian);
return dtDateTime;
}
Now I am calling GetdatetimedetailsinIST(5/6/2014 8:00:00 AM,"240");
and it will reurn Indian Time 5/6/2014 5:30:00 PM.
Now I want to get back the 5/6/2014 8:00:00 AM for another scenario by using value 5/6/2014 5:30:00 PM.
What are the changes need to do in the above function?
Please help.
howeverCould you add a string timeZoneToConvertTo parameter to your convert method?
public static DateTime DateTimeConvert(DateTime nonConvertedDateTime, string timeoffsetvalue, string timeZoneToConvertTo)
{
TimeZoneInfo tzinfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneToConvertTo);
DateTime dtDateTime = nonConvertedDateTime.AddMinutes(Convert.ToInt32(timeoffsetvalue));
dtDateTime = TimeZoneInfo.ConvertTimeFromUtc(dtDateTime, tzinfo);
return dtDateTime;
}
Console.WriteLine(DateTimeConvert(new DateTime(2014, 5, 6, 8, 00, 00), "240", "India Standard Time").ToString());
Console.WriteLine(DateTimeConvert(new DateTime(2014, 5, 6, 8, 00, 00), "240", "Central Standard Time").ToString());
You still need to handle any exceptions resulting from an inability to find the timezone.
I don't understand why you want an offset instead of using the ToUniversal() extension, however, that is your choice.
Adding minutes manually is seldom required or recommended. Also, there are a lot of unnecessary strings floating around your method. Consider the following instead:
public static DateTime ConvertToIndiaTime(DateTime dateTime, int offsetMinutes)
{
// Create a DateTimeOffset from the input values.
// This assumes positive offset values are *WEST* of UTC,
// such as if it came from the getTimeZoneOffset function of
// JavaScript's Date object.
TimeSpan offset = TimeSpan.FromMinutes(-offsetMinutes);
DateTimeOffset dto = new DateTimeOffset(dateTime, offset);
// Convert the DateTimeOffset to the desired time zone
DateTimeOffset converted =
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dto, "Indian Standard Time");
// Return the DateTime portion, representing the local time in India.
return converted.DateTime;
}
You would call it like this:
// get a DateTime object
DateTime dt = DateTime.ParseExact("5/6/2014 8:00:00 AM",
"M/d/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture);
// get the offset as an integer
int offsetMinutes = 240;
// call the conversion method
DateTime indiaTime = ConvertToIndiaTime(dt, offsetMinutes);
Your method seems to combine two separate DateTime operations into one - hence it's not easy for you to reverse the operation. How about the following structure:
private static readonly TimeZoneInfo IstTimeZone =
TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
public static DateTime ConvertDateTimeUtcToIst(DateTime toConvert)
{
return TimeZoneInfo.ConvertTimeFromUtc(toConvert, IstTimeZone);
}
public static DateTime ConvertDateTimeIstToUtc(DateTime toConvert)
{
return TimeZoneInfo.ConvertTimeToUtc(toConvert, IstTimeZone);
}
Usage:
var converted = ConvertDateTimeUtcToIst(DateTime.Parse("5/6/2014 8:00:00 AM"))
.AddMinutes(240);
var reverted = ConvertDateTimeIstToUtc(converted).AddMinutes(-240);
Or if you absolutely need to have it in one method:
public static DateTime ConvertDateTimeUtcToIst(
DateTime toConvert, int offset = 0)
{
return TimeZoneInfo.ConvertTimeFromUtc(toConvert, IstTimeZone)
.AddMinutes(offset);
}
public static DateTime ConvertDateTimeIstToUtc(
DateTime toConvert, int offset = 0)
{
return TimeZoneInfo.ConvertTimeToUtc(toConvert, IstTimeZone)
.AddMinutes(offset);
}
Usage:
var converted = ConvertDateTimeUtcToIst(
DateTime.Parse("5/6/2014 8:00:00 AM"), 240);
var reverted = ConvertDateTimeIstToUtc(converted, -240);

How to turn DateTime to last day of the month?

If I have a DateTime which is, for example, 2012-05-24, what is the quickest way to convert it to a date which is the last day of that month (2012-05-31).
Well you can use:
DateTime date = ...;
var endOfMonth = new DateTime(date.Year, date.Month,
DateTime.DaysInMonth(date.Year, date.Month));
Note that that will create a DateTime with a Kind of Unspecified. You should consider what Kind you really want. (Or use my Noda Time library, where you'd use a LocalDate instead.)
Here's some extension methods I use:
public static class DateTimeExtensionMethods
{
public static DateTime StartOfMonth(this DateTime date)
{
return new DateTime(date.Year, date.Month, 1);
}
public static DateTime EndOfMonth(this DateTime date)
{
return date.StartOfMonth().AddMonths(1).AddSeconds(-1);
}
}
Note that in my case I'm using them for SQL queries, so I want it to be up to the last second of the last day of the month.
Based on comments, yes, if you want just want the date and not time, you could use:
public static DateTime EndOfMonth(this DateTime date)
{
return date.StartOfMonth().AddMonths(1).AddDays(-1);
}
Or just use the Date property of the result to just get the date portion, then it satisfies both cases depending how you use it.
Try this
DateTime dt = DateTime.Parse("2012-05-24");
DateTime lastDate = new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month));
Try this
DateTime date = new DateTime(2012, 05, 24);
DateTime endOfMonth = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
Output: 5/31/2012 12:00:00 AM
You can then modify this to your required format.

how to get the three previous dates for the given date .net

I would like to get the 3 dates from the current date or if user enters a date like 16/07/2011 i would like to show the 3 previous dates for this like
15/07/2011,14/07/2011,13/07/2011
Simple steps:
Parse the date to a DateTime. If you know the format to be used, I would suggest using DateTime.ParseExact or DateTime.TryParseExact.
Use DateTime.AddDays(-1) to get the previous date (either with different values from the original, or always -1 but from the "new" one each time)
For example:
string text = "16/07/2011";
Culture culture = ...; // The appropriate culture to use. Depends on situation.
DateTime parsed;
if (DateTime.TryParseExact(text, "dd/MM/yyyy", culture, DateTimeStyles.None,
out parsed))
{
for (int i = 1; i <= 3; i++)
{
Console.WriteLine(parsed.AddDays(-i).ToString("dd/MM/yyyy"));
}
}
else
{
// Handle bad input
}
Just use the TimeSpan object or AddDays function. Here are example extension methods where you can modify days easily:
public static DateTime SubtractDays(this DateTime time, int days)
{
return time - new TimeSpan(days, 0, 0, 0);
}
public static DateTime SubtractDays(this DateTime time, int days)
{
return time.AddDays(days)
}

Categories

Resources