Best way to get the current month number in C# - c#

I am using C# to get current month number:
string k=DateTime.Now.Month.ToString();
For January it will return 1, but I need to get 01. If December is the current month, I need to get 12. Which is the best way to get this in C#?

string sMonth = DateTime.Now.ToString("MM");

Lots of different ways of doing this.
For keeping the semantics, I would use the Month property of the DateTime and format using one of the custom numeric format strings:
DateTime.Now.Month.ToString("00");

using System;
class Program
{
static void Main()
{
//
// Get the current month integer.
//
DateTime now = DateTime.Now;
//
// Write the month integer and then the three-letter month.
//
Console.WriteLine(now.Month);
Console.WriteLine(now.ToString("MMM"));
}
}
Output
5
May

DateTime.Now.Month.ToString("0#")

Related

Turn wrong date string to nearest valid one

For example I have 31.09.2017 (which is NON existent date) and that string's DateTime.ParseExact("31.09.2017", "dd.MM.yyyy", null); returns System.FormatException exception. Is there a way to turn 31.09.2017 into 30.09.2017 and do the same for all such wrong dates? For example like "round" works: to move to previous month's last day or next month's first day.
You can use the following technique :
DateTime temp;
if (!DateTime.TryParse("31.09.2017", out temp))
temp = GetValidDate("31.09.2017");
DateTime GetValidDate(string _date)
{
int day, year, month;
day = int.Parse(_date.Substring(0, 2));
month = int.Parse(_date.Substring(3, 2));
year = int.Parse(_date.Substring(6, 4));
return new DateTime(year, month, Math.Min(day, DateTime.DaysInMonth(year, month)));
}
The result may be unpredictable but your could split parts, convert to an int, then ensure that each part is within the correct range, then create a new string to parse. I suspect you only need to do this for the first 2 parts (dd and MM) and if outside of the range just set to the closest bounding value.
You can write a custom format provider and use it with DateTime.ParseExact however it may not work across cultures and may still throw exceptions like The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar. depending on how you implement.
DateTime.ParseExact Method (String, String, IFormatProvider)
An example.

C# How do I convert two or more integers into a date?

How do I convert two integers for instance 28 and 03 into a date like "28.03".
The integers should be input from the user and then converted to the date.
Also, how do I add days to the date?
Just an implementation for your example:
public static string GetDateString(int month, int day)
{
return new DateTime(DateTime.Now.Year, month, day).ToString("dd.MM");
}
To add days to a date you can use the DateTime.AddDays() method:
DateTime date = DateTime.Now;
DateTime otherDate = date.AddDays(7);
The links mentioned by #Giorgi and #D. Petrov are also very useful.
UPDATE:
Here is an example based on your comment.
class ConsoleApp
{
public void Main(string[] args)
{
int day = int.Parse(Console.ReadLine());
int month = int.Parse(Console.ReadLine());
string formattedDate = GetDateString(month, day);
Console.WriteLine(formattedDate);
// You cannot initialize a DateTime struct only with month and day.
// Because Year is not relevant we use the current year.
DateTime date = new DateTime(DateTime.Now.Year, month, day);
DateTime otherDate = date.AddDays(5);
Console.WriteLine(GetFormattedDate(otherDate));
}
public static string GetFormattedDate(DateTime date)
{
// The ToString() method accepts any custom date format string.
// Here is how you can create a custom date format string:
// https://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx
// dd: days in two digits
// MM: months in two digits
return date.ToString("dd.MM");
}
public static string GetDateString(int month, int day)
{
// Here we construct a DateTime struct
DateTime date = new DateTime(DateTime.Now.Year, month, day);
// Now we extract only the day and month parts.
return GetFormattedDate(date);
}
}
Well if 28 is day and 03 month - you can pass these parameters to the constructor of DateTime structure object. Once you initialize a DateTime object there are various ways to convert it as string. It also has AddDays method.
There is plenty of documentation about what you need (in particular - the DateTime structure). The most relevant information about your current need and the different ways to format yor string with the date you can find here: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
But as I mentioned before, there is plenty of information in the web.

I want to covert julian date(YYJJJ format) to any normal date format(MMDDYY) using c#. Is there any defined function for that?

Hi I have julian date string YYJJJ format. eg 05365(31st dec 2005). I want to covert to MMDDYY format(123105).
Is there any defined function for that in?
I faced same problem as I was try to convert dates from BACS 18 standard to a String. I couldn't find ready solution to this problem so I wrote this function:
private String bacsDateConvert(String bacsFormatDate)
{
int dateYear = Convert.ToInt16(bacsFormatDate.Substring(1, 2));
int dateDays = Convert.ToInt16(bacsFormatDate.Substring(3, 3));
DateTime outputDate = new DateTime();
outputDate = Convert.ToDateTime("31-12-1999");
outputDate = outputDate.AddYears(dateYear);
outputDate = outputDate.AddDays(dateDays);
String outputString = outputDate.ToString("yyyyMMdd");
return outputString;
}
//You may call it like this:
textBox4.Text = Convert.ToString(bacsDateConvert(bacsTxnValueDate));
You also may modify it slightly and easily make it return DateTime data type if you want to. I just needed to return a string in the above format.
First of all, there is no YY, JJJ and DD formats as a custom date and time format. One solution might be to split your string Year and DayOfYear part and create a DateTime with JulianCalendar class.
string s = "05365";
int year = Convert.ToInt32(s.Substring(0, 2));
// Get year part from your string
int dayofyear = Convert.ToInt32(s.Substring(2));
// Get day of years part from your string
DateTime dt = new DateTime(1999 + year, 12, 18, new JulianCalendar());
// Initialize a new DateTime one day before year value.
// Added 1999 to year part because it makes 5 AD as a year if we don't.
// In our case, it is 2004/12/31
dt = dt.AddDays(dayofyear);
// Since we have a last day of one year before, we can add dayofyear to get exact date
I initialized this new DateTime(.. part with 18th December because
From Julian Calendar
Consequently, the Julian calendar is currently 13 days behind the
Gregorian calendar; for instance, 1 January in the Julian calendar is
14 January in the Gregorian.
And you can format your dt like;
dt.ToString("MMddyy", CultureInfo.InvariantCulture) //123105
I honestly didn't like this way but this is the only one I can imagine as a solution.

Date Comparing in C#

i'm currently working on a little project and i'm stuck with a little problem.
I would like my program to call a method CheckDate on boot.
This method would read in a .txt file to see the last saved date in (yyyy/mm/dd) format.
Then it would compare it with todays date and if it's not the same go on with some instructions.I've read the doc here but can't quite find which method best suites my need.
Question 1: Is there a way to get today's date in (yyyy/mm/dd) format?
Question 2: What's the easiest way to compare Dates in C#?
Thanks in advance.
1. DateTime.Now.ToString("yyyy/MM/dd")
2. DateTime.Parse(input).Date == DateTime.Now.Date
You can get today's date as a string by simply formatting a date.
String today = String.Format("{0: yyyy/MM/dd}", DateTime.Now);
String today = DateTime.Now.ToString("yyyy/MM/dd");
I would advise against using a text file as your means of saving data but if you are going with that system the only thing you would have to do is check to see if the date from the text file matches the date you formatted. Simply comparing formatted strings should do the trick.
if (string a == string b)
You could even put it in one line without having to format stuff separately
if (DateTime.Now.ToString("yyyy/MM/dd").Equals("date pulled from txt file"))
What's the easiest way to compare Dates in C#?
Store them not as text but in a DatteTime.
Compare the variables.
If there is a time in both, compare a.Date == b.Date.
Is there a way to get today's date in (yyyy/mm/dd) format?
Yes. This is wrong, though. PARSE The wrong input and compare the parsed data.
There is a DateTime.Compare method that you could use http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx - this should also let you use the built-in < and > operators.
By the letter of the question:
1:
DateTime.Now.ToString(#"yyyy\/MM\/dd")
2:
if(d1 < d2)...
if(d2 >= d1)...
etc.
However.
DateTime dt;
if(DateTime.TryParseExact(readInString, "yyyy-MM-dd", null, DateTimeStyles.AssumeLocal, out dt))
{
if(dt != DateTime.Now.Date)
{
//Code for case where it's no longer that day goes here.
}
}
else
{
//Code for someone messed up the file and it's not a valid date any more goes here.
}
You're doing this for computer-reading, not human-reading, so use the standard format rather than the conventional format (standard as in ISO, but also every country except North Korea has it as the national standard): yyyy-MM-dd (Edit: I see you're in Canada, CSA Z234.5:1989 is the relevant national standard on date-times for technical purposes; it says to use yyyy-MM-dd).
You should do it the other way around, read the string, parse the date, and do the comparison.
you might want to have a look at the FileInfo-Class ... you can compare the LastWriteTime Member to DateTime.Today
DateTime d1 = DateTime.Now;
DateTime d2 = d1.AddMilliseconds(123456789);
string formattedDate = d1.ToString("yyyy/MM/dd");
TimeSpan ts = d2 - d1;
double dayDiff = ts.TotalDays;
double hourDiff = ts.TotalHours;
double minuteDiff = ts.TotalMinutes;
double secondDiff = ts.TotalSeconds;
double milDiff = ts.TotalMilliseconds;
Console.WriteLine("Formatted Date: {0}\r\nDate Diff:\r\nTotal Days: {1}; Total Hours: {2}; Total Minutes: {3}; Total Seconds: {4}; Total Milliseconds: {5}", formattedDate,dayDiff,hourDiff,minuteDiff,secondDiff,milDiff);
Output:
Formatted Date: 2011/12/15
Date Diff:
Total Days: 1.42889802083333; Total Hours: 34.2935525; Total Minutes: 2057.61315; Total Seconds:
123456.789; Total Milliseconds: 123456789
*Edited my initial post to clarify how the "Total" properties work.
//use a TimeSpan do something like this
strCurDate = string.Format(DateTime.Now.ToString(), "yyyy/mm/dd");
FileInfo fiUpdateFileFile = null;
fiUpdateFileFile = new FileInfo(YourFile Location + Your FileName);
if (((TimeSpan)(DateTime.Now - fiUpdateFileFile.LastWriteTime)).TotalHours < 24)
{
// do your logic here...
}
// you could also get at DateTime.Now.Date() or Day.. depending on what you want to do

How would I make a datetime into a specific custom format?

Say the current date is 1st Mar 2010, I want to display it like this...
20100301 so like first 4 digits = year, 2 digits = Month, 2 digits = day
is there an easy way to do this?
use format
yourdatetimeObj.ToString("yyyyMMdd");
Ref: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Something like
dateTimeObject.ToString("yyyyMMdd");
See String Format for DateTime
var mydate = DateTime.Now; // Whatever you want.
mydate.ToString("yyyyMMdd");
Look at DateTimeFormatInfo for the other custom format strings you can use.
You can either use the ToString() implementation of the DateTime class, like the examples already given, or use a format string to display it along with other information, like so:
var now = DateTime.Now;
var msg = String.Format("Now: {0:dd/MM/yyyy}", now);
Or
Console.Write("Now: {0:MM/dd/yyyy}", now);

Categories