How to get yesterday's date in C# - c#

I want to retrieve yesterday's date in my ASP.NET web application using C#.
I've tried searching for a solution but have not had much success. The code I'm using just outputs today's date:
string yr = DateTime.Today.Year.ToString();
string mn = DateTime.Today.Month.ToString();
string dt = DateTime.Today.Day.ToString();
date = string.Format("{0}-{1}-{2}", yr, mn, dt);
How can I get yesterday's date?

Use DateTime.AddDays() method with value of -1
var yesterday = DateTime.Today.AddDays(-1);
That will give you : {6/28/2012 12:00:00 AM}
You can also use
DateTime.Now.AddDays(-1)
That will give you previous date with the current time e.g. {6/28/2012 10:30:32 AM}

The code you posted is wrong.
You shouldn't make multiple calls to DateTime.Today. If you happen to run that code just as the date changes you could get completely wrong results. For example if you ran it on December 31st 2011 you might get "2011-1-1".
Use a single call to DateTime.Today then use ToString with an appropriate format string to format the date as you desire.
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");

You don't need to call DateTime.Today multiple times, just use it single time and format the date object in your desire format.. like that
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
OR
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");

You will get yesterday date by this following code snippet.
DateTime dtYesterday = DateTime.Now.Date.AddDays(-1);

var yesterday = DateTime.Now.AddDays(-1);

Something like this should work
var yesterday = DateTime.Now.Date.AddDays(-1);
DateTime.Now gives you the current date and time.
If your looking to remove the the time element then adding .Date constrains it to the date only ie time is 00:00:00.
Finally .AddDays(-1) removes 1 day to give you yesterday.

string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");

DateTime dateTime = DateTime.Now ;
string today = dateTime.DayOfWeek.ToString();
string yesterday = dateTime.AddDays(-1).DayOfWeek.ToString(); //Fetch day i.e. Mon, Tues
string result = dateTime.AddDays(-1).ToString("yyyy-MM-dd");
The above snippet will work. It is also advisable to make single instance of DateTime.Now;

DateTime.Today as it implies is todays date and you need to get the Date a day before so you subtract one day using AddDays(-1);
There are sufficient options available in DateTime to get the formatting like ToShortDateString depending on your culture and you have no need to concatenate them individually.
Also you can have a desirable format in the .ToString() version of the DateTime instance

Related

Convert DateTime 1/20/2022 8:48:30 PM to 20/01/2022 8:48:30 PM C#

I basically have two DateTime variables
DateTime dateToday = WorldTimeAPI.Instance.GetCurrentDateTime();
DateTime dateFinish;
dateToday gets current date from the web, with this format 1/20/2022 8:48:30 PM.
dateFinish has this other format 20/01/2022 8:48:30 PM, the day first, and then the month, everything else is the same.
I want to be able to parse one of them to match the other one in terms of format so that I can compare them both to know if todays date is greater than date finish by doing this:
if(dateToday.CompareTo(dateToEndMission) > 0)
{do stuff}
I tried looking at documentation but it has so many different formats that I just couldnt figure out the exact way to do it.
To compare two dateTime values in an if statement you can do:
if(firstDate.Date > secondDate.Date)
{
//Do something...
}
Try and keep things as simple as possible.
As stated above you can compare date time with the > operator. But I would go further and ask why you're using that api to get the current date and time when you could just use this
DateTime today = DateTime.Now;
This should fix your problem, because you should be initialising date time in the same way now. If not, then I suggest you take a look at this other questions answers:
Convert DateTime to a specified Format
You can try the ParseExact method
DateTime dateToday = DateTime.Now;
DateTime dateFinish = DateTime.ParseExact("20/01/2022 10:56:09", "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
if (dateToday > dateFinish)
{
// do something
}

DateTime.ToString issue

I try to display a DateTime with the "general date short time" format.
When I use the g specifier, it gives me something like 01-08-13 10:12:00 10:12 instead of 01-05-13 10:12.
It seems to duplicate the time and I don't know why.
Anyone?
Edit 1
Here is the code I use:
var startDate = DateTime.MinValue.ToString("g");
if (Airspace.StartDate != null)
startDate = ((DateTime)Airspace.StartDate).ToString("g"); //01-08-13 00:00:00 00:00
Edit 2
The same issue occurs when I use "short date pattern":
var startDate = DateTime.MinValue.ToString("d");
if (Airspace.StartDate != null)
startDate = ((DateTime)Airspace.StartDate).ToString("d"); //01-08-13 00:00:00
It doesn't make sense!
The "d" format specifier applies the short date pattern and "g" is a concatenation of the short date and short time patterns. So based on your results, you somehow have a short date pattern with time components in it. I can reproduce your results by setting such a short date pattern explicitly, like so:
Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd HH:mm:ss";
Console.WriteLine(DateTime.Today.ToString("g")); // 2008-05-11 00:00:00 00:00
Console.WriteLine(DateTime.Today.ToString("d")); // 2008-05-11 00:00:00
I think the real question is how you ended up with what looks like some very strange culture settings! I tried enumerating the set of supported cultures and looking for one whose short date format included time specifiers, like so:
foreach (var culture in CultureInfo.GetCultures(CultureTypes.AllCultures)
.OrderByDescending(c => c.DateTimeFormat.ShortDatePattern.Length))
{
Console.WriteLine($"{culture.Name} {culture.DateTimeFormat.ShortDatePattern}");
}
But in several hundred cultures I came up with nothing. So, can you find anything anywhere in your code that's building up a CultureInfo object and assigning it as the current culture? If yes, maybe there's a mistake in that code somewhere.
Hope this can help you:
DateTime today = DateTime.Now;
Console.WriteLine(today.ToString("dd-MM-yy H:mm"));
//Result: 01-08-13 04:33
Console.ReadLine();
Other format: http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
Try this
startDate = DateTime.Now.ToString(System.Globalization.CultureInfo.
CurrentCulture.DateTimeFormat);

.NET Date Add Days

I have date in this format "1999-05-31T13:20:00.000-05:00" I want to add some hours or days to it . Can some one suggest how to do that with this format and AddDays or AddHours ? Result need to return same format.
Try using DateTimeOffset.Parse. Then use AddDays or AddHours.
It is important to use DateTimeOffset instead of DateTime if you want to preserve the same timezone offset that you parsed.
var dateTimeOffset = DateTimeOffset.Parse("1999-05-31T13:20:00.000-05:00");
var newDateTimeOffset = dateTimeOffset.AddHours(1);
var newDateTimeString = newDateTimeOffset.ToString("O");
if you don't like the way "O" formats, you can use this:
var newDateTimeString = newDateTimeOffset.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK")
This will 100% match to your format.
Example:
txt_del.Text = Calendar1.SelectedDate.ToString("MM/dd/yyyy");
/* for date picking textbox*/
double d2 = double.Parse(txt_till.Text);
/*second textbox for number of days to add*/
DateTime tom = Calendar1.SelectedDate.AddDays(d2);
/*for adding number of days to selected date*/
txt_total.Text = tom.ToString("MM/dd/yy")
Use DateTime.Parse(...) to create a DateTime object. Then you can add days and/or hours, and then ToString() to get the new string.
That looks like datetimeoffset. Perhaps from sql server? You should be able to use the datetimeoffset structure and the parse method. Once you have a datetimeoffset type you can use addhours or related methods.

Watin : Get Datetime and perform calculation

I have a textfield that has a date with the format "12/23/2010".Is there away for me to get the number 23 using watin ie get number from textfield;i'm gonna use it like this.
1.Get datetime 12/23/2010 and get number '23'
2.substract 2 from 23 and store it somewhere[ie: 23 - 2 = 21]
3.Insert the new datetime number [ie:12/21/2010 ]
string myDate = browser.TextField(Find.ByName("myTextField")).Value;
DateTime time = = new DateTime();
time2 = time - 2;
browser.TextField(Find.ByName("myTextField")).TypeText(time2);
Is this possible?or should i be looking to another way.Ask the user to insert the data instead.
You should use DateTime.Parse, DateTime.TryParse, DateTime.ParseExact or DateTime.TryParseExact to parse from text to a DateTime.
If a failure to parse indicates a failure in the code somewhere (which is probably the case here, given that it's a test) I suspect DateTime.ParseExact is the most appropriate approach, providing the expected format, culture etc.
if what you want is to subtract 2 days from a date I would do it like this:
DateTime dt = DateTime.Parse(myDate)-TimeSpan.FromDays(2);
//its steps 1,2 & 3 in one easy to read line :)
This is of course if you are sure the string you have IS a valid date. If it might not be, then you should do what the Skeet recommends, which is using first a try parse, checking if the return value is true, and if it is, then do the rest, and if it is not, send an error message.
consider writing
DateTime dt = Convert.ToDateTime(myDate);
DateTime dtNew = new DateTime(dt.Year, dt.Month, dt.Day - 2);
browser.TextField(Find.ByName("myTextField")).TypeText(dtNew.ToShortDateString());
Try getting the value of the date as string
Convert it to datetime and use AddDays we can use negative or positive value
And insert it into textbox
string myDate = this.Elements.textfield.Value;
DateTime dt = Convert.ToDateTime(myDate);
DateTime dtNew = dt.AddDays(-3);
this.Elements.ChangeDateActive.TypeText(dtNew.ToShortDateString());
That's it thanks

C# Getting Just Date From Timestamp

If I have a timestamp in the form: yyyy-mm-dd hh:mm:ss:mmm
How can I just extract the date from the timestamp?
For instance, if a timestamp reads: "2010-05-18 08:36:52:236" what is the best way to just get 2010-05-18 from it.
What I'm trying to do is isolate the date portion of the timestamp, define a custom time for it to create a new time stamp. Is there a more efficient way to define the time of the timestamp without first taking out the date, and then adding a new time?
DateTime.Parse("2010-05-18 08:36:52:236").ToString("yyyy-MM-dd");
You should use the DateTime type:
DateTime original = DateTime.Parse(str);
DateTime modified = original.Date + new TimeSpan(13, 15, 00);
string str = modified.ToString("yyyy-MM-dd HH:mm:ss:fff");
Your format is non-standard, so you'll need to call ParseExact instead of Parse:
DateTime original = DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss:fff", CultureInfo.InvariantCulture);
You could use substring:
"2010-05-18 08:36:52:236".Substring(0, 10);
Or use ParseExact:
DateTime.ParseExact("2010-05-18 08:36:52:236",
"yyyy-MM-dd HH:mm:ss:fff",
CultureInfo.InvariantCulture)
.ToString("yyyy-MM-dd");
DateTime date;
if (DateTime.TryParse(dateString, out date))
{
date = date.Date; // Get's the date-only component.
// Do something cool.
}
else
{
// Flip out because you didn't get a real date.
}
Get the .Date member on the DateTime
DateTime date = DateTime.Now;
DateTime midnightDate = date.Date;
use it like this:
var x = DateTime.Now.Date; //will give you midnight today
x.AddDays(1).AddTicks(-1); //use these method calls to modify the date to whats needed.
The best (and fastest) way to do this is to convert the date to an integer as the time part is stored in the decimal part.
Try this:
select convert(datetime,convert(int, #yourdate))
So you convert it to an integer and then back to a data and voila, time part is gone.
Of course subtracting this result from the original value will give you the time part only.

Categories

Resources