Strange behaviour when get current month in C# - c#

This is small code. But I couldn't find whats wrong with it. In my application I want to get the current month in long month format(ex:January). I used the following two lines of code.
DateTime now = DateTime.Now;
string month = now.Month.ToString("MMMM",CultureInfo.CurrentCulture);
but its return "MMMM" for the values of month. Can anybody tell me whats wrong in this code.

now.Month is the int representation the month e.g. 1 for January, that's why the .ToString("MMMM") works "strange".
What you need is to call the .ToString() directly on the DateTime object:
DateTime now = DateTime.Now;
string month = now.ToString("MMMM",CultureInfo.CurrentCulture);

String month =
System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(
DateTime.Now.Month);

Related

How to set default month and day in the datetimepicker?

I have searched online and i only managed to find codes to set the year month and day.
dateTimePicker2.Value = new DateTime(2017,12,31);
I tried using the custom format and it does not seem to work
dateTimePicker2.CustomFormat = "DD/MM";
dateTimePicker2.Value = new DateTime(12,31);
You cannot create DateTime object only from day and month. DateTime simply doesn't have this kind of constructor. DateTime Constructors
So you need to go with some kind of "workaround"
- Use "dummy" year and when you need to use a date - use only Month and Day properties.
var dummyYear = 2000;
dateTimePicker2.Value = new DateTime(dummyYear, 12, 31);
Another workaround will be to use ParseExact method which will create DateTime based on the format you are using "dd/MM"
var date = DateTime.ParseExact("31/12", "dd/MM", CultureInfo.InvariantCulture);
dateTimePicker2.Value = date; // 12/31/2017
Notice that when you did not provide a year - current year will be used.
Another notice: DD is invalid format for days it should be lower case "dd"
You cannot partially set the date without a year, it's not valid.
What you cand do is specify the month and date in code as "default" values, and get the current year programmtically (or whatever year you want), and use that value for the year.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "dd/MM";
dateTimePicker1.Value = DateTime.Now;

C# - Getting the current day of the month without month/year

Is there any way to get the day of the month as an int/string? E.G it's the 5th of June, I want the system to return 5 to me.
Easily you can get the day of month by returning
DateTime.Today.Day
Use the DateTime.Day property.
var dt = DateTime.Now;
var day = dt.Day;
sure,
as an integer, it's just DateTime.Today.Day
as a string it's DateTime.Today.Day.ToString("0")

Calculate the annual use of a service starting from the date of signing

I need to calculate the annual use of a service starting from the date of signing. Something like:
select Count(*) from TABLENAME where Date >= MYDATE
MYDATE need to be calculate from a subscription date and I need to get the last year date from subscription referring to the current date
Some examples:
subscription date: 2007-06-29
if current date is : 2015-04-29 then date is: 2014-06-29
if current date is : 2015-06-29 then date is: 2015-06-29
if current date is : 2015-06-29 then date is: 2015-06-29
I'm using c# to calculate the date but it crashes in leapyear:
var date = new DateTime(DateTime.Now.Year, subscriptionDate.Month, subscriptionDate.Day);
if (DateTime.Now.Date < date)
{
date = date.AddYears(-1);
}
I was wondering if there were a clever/better way to do it in c# or mysql also handling leapyear
---UPDATE----
Running example with suggested solutions
Well, I'd do it in Noda Time, myself:
LocalDate subscriptionDate = ...;
LocalDate today = ...; // Need to take time zone into account
int years = Period.Between(subscriptionDate, today);
return subscription.PlusYears(years);
With .NET that would be slightly harder, but I'd still go for the approach of adding years (and letting it do the truncation for Feb 29th):
// Only call this *once* - otherwise you could get inconsistent results
DateTime today = DateTime.Today;
int years = today.Year - subscriptionDate.Year;
DateTime candidate = subscriptionDate.AddYears(years);
// We might have overshot, in which case lower the number of years.
return candidate <= today ? candidate : subscriptionDate.AddYears(years - 1);
Thanks to Yuri Dorokhov answer and Jon Skeet suggestion
I found a solution that works well and handle leap year:
int year = DateTime.Now.DayOfYear >= subscriptionDate.DayOfYear ?
DateTime.Now.Year : DateTime.Now.Year - 1;
var date = new DateTime(year, 1, 1).AddDays(subscriptionDate.DayOfYear - 1);
--------UPDATE------
I leave here this answer as reference but it does not handle well leap year so don't use it
Use mysql DATE_SUB function
DATE_SUB(Date, INTERVAL 1 YEAR)

How to get yesterday's date in 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

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

Categories

Resources