I am trying to create a DateTime object, but it seems to be giving me an error.
int month = "1"
int year = "2017"
DateTime date = new DateTime(year, month, DateTime.Day);
It doesn't seem to like DateTime.Day. It says an object reference is required for the non-static field.
How could I get today's day(16th) as a parameter? Also, I need the date to have hh:mm:sss... how could I do that?
Thanks for your help!
Use
var day = DateTime.Now.Day;
for today.
You can add hh:mm:sss to the date object in the constructor too:
DateTime date = new DateTime(year, month, DateTime.Now.Day, 10, 11, 12);
10 => hours
11 => minutes
12 => seconds
Of course you can use DateTime.Now.Hour etc. for the current values.
An ArgumentOutOfRangeException is thrown if the values are not valid for a real date, e.g. 30.2.xxxx.
You can print the date object in different formats, read the MS Documentation for all possibilities.
It should be:
int month = 1;
int year = 2017;
DateTime date = new DateTime(year, month, DateTime.Now.Day);
Take note, you declare integer without quotation marks:
int month = 1;
To convert it on 24 hour format with milliseconds as requested on comment:
string strResult = string.Format("{0:MM/dd/yyyy HH:mm:ss.fff}", date);
//Results: 02/17/2017 00:00:00.000
For 12 hour:
string strResult = string.Format("{0:MM/dd/yyyy hh:mm:ss.fff}", date);
//Results: 02/17/2017 12:00:00.000
Related
When my application starts I have a datetimepicker for a start time and end time.
dvSubmittedDateBegin.Format = DateTimePickerFormat.Custom;
dvSubmittedDateBegin.CustomFormat = "MMM dd yyyy - hh mm tt";
Everything works. However I've been asked to have the start default default at 5AM.
I created a new datetime and assigned the dvSubmittedDateBegin.Value - dt;
However the new datetime I guess I have to specify every int?
DateTime dt = new DateTime(2015, 6, 24, 05, 00, 0);
What happens tomorrow when its 6/25? Not sure how to fix this.
How about like;
DateTime dt = DateTime.Today + TimeSpan.FromHours(5);
or more simple
DateTime dt = DateTime.Today.AddHours(5);
You will get the current date from midnight with DateTime.Today and you will add 5 hours to it and it will be 5 AM of the current day.
You can use the AddDays(), AddHours(), AddMinutes() etc. methods:
DateTime dt = DateTime.Today.AddHours(5);
You can create a function that would return a particular date where you pass all the components and define time components as default parameters:
DateTime CreateDateWith5amStart(int year, int month, int day, int hour = 5, int minute = 0, int second = 0)
{
return new DateTime(year, month, day, hour, minute, second)
}
If they provide only date components, it will set time to 5 a.m. If they need a different time, they can provide time components.
I am trying to find days between two dates using a Time span.
nextdate1='2014-12-20'
today `='2014-12-18'`
My sample code is:
DateTime nexdate1 = dr.GetDateTime(2); //gets from database. I checked and the value is correct
DateTime today = DateTime.Now;
TimeSpan nextdate = nexdate1.Subtract(today);
int difference = nextdate.Days;
Now I get difference=1. Actually the difference is 2 (20-18).
Why it shows difference as 1?
TimeSpan.Days is an int. Your answer is getting truncated.
In the following code:
var date1 = DateTime.Parse("Dec 12, 2014");
var date2 = DateTime.Parse("Dec 14, 2014");
var difference = (date2 - date1).Days;
difference is set to 2.
But in this code:
var date1 = DateTime.Parse("Dec 12, 2014 12:01 AM");
var date2 = DateTime.Parse("Dec 14, 2014");
var difference = (date2 - date1).Days;
difference is set to 1.
When we look at the timespan date2 - date1, we get the following:
{1.23:59:00}
Days: 1
Hours: 23
Minutes: 59
Seconds: 0
TotalDays: 1.9993055555555554
You should set nextDate = nexdate1.Date.Subtract(DateTime.Today); so that you're only looking at the difference in days, or take (int)Math.Round(nextDate.TotalDays)
Actually your datetime variable having time part, because of that time your result get affected. Hence you have to find only date part of your datetime value:
Use DateTime.Date
Do it like this:
DateTime nexdate1 = dr.GetDateTime(2);
DateTime today = DateTime.Now;
TimeSpan nextdate = nexdate1.Date.Subtract(today.Date); // Here find only date part from datetime value.
//TimeSpan nextdate = nexdate1-today
int difference = nextdate.Days;
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.
I have a calendar that's first week day starts in Sunday and ends in Saturday.
Right now I can only disable days in the calendar current month because I don't know the first and last day in the calendar.
The code that Im using is pretty simple right now:
private List<DateTime> GetDisabledDates(DateTime fromDate, DateTime toDate){
// right now fromDate and toDate are the start and end days in a month
var disabledDates = SearchDates(fromDate, toDate);
return disabledDates;
}
So, what I need is to get the first day and last day showed in the calendar month, considering that week starts in Sunday and ends in Saturday.
Any clue on how to dinamically get first and last (yellow marked dates) from a specific month? Considering the calendar configuration?
Well for the first day in this view something like this should do it
//Using UTC to counter daylight saving problems
var month = new DateTime(2014, 8, 1, 0, 0, 0, DateTimeKind.Utc);
var firstInView = month.Subtract(TimeSpan.FromDays((int) month.DayOfWeek));
For the remaining days you just need to calculate the amount left in (7 * NumRows) - (DaysOfCurrentMonth + DaysOfPreviousMonth), where DaysOfPreviousMonth is the DayOfWeek property of this month first day again.
The solution that works for me:
int totalCalendarDays = 42; // matrix 7 x 6
// set the first month day
DateTime firstDayMonth = new DateTime(date.Year, date.Month, 1);
// set the lastmonth day
DateTime lastDayMonth = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
// now get the first day week of the first day month (0-6 Sun-Sat)
byte firstDayWeek = (byte) firstDayMonth.DayOfWeek;
// now get the first day week of the last day month (0-6 Sun-Sat)
byte lastDayWeek = (byte) lastDayMonth.DayOfWeek;
// now the first day show in calendar is the first day month minus the days to 0 (sunday)
DateTime firstDayCalendar = firstDayMonth.Subtract(TimeSpan.FromDays(firstDayWeek));
int tempDays = (lastDayMonth - firstDayCalendar).Days;
DateTime lastDayCalendar = lastDayMonth.Add(TimeSpan.FromDays(totalCalendarDays - tempDays - 1));
Maybe is a better way to do this :)
HereĀ“s my suggestion, defining year and month as parameters:
public DateTime[] GetMonthDisplayLimits(int year, int month)
{
int lastDay = DateTime.DaysInMonth(year, month);
var firstDayInMonth = new DateTime(year, month, 1);
var lastDayInMonth = new DateTime(year, month, lastDay);
var firstDayInView = firstDayInMonth.AddDays(-1 * (int) firstDayInMonth.DayOfWeek);
var lastDayInView = lastDayInMonth.AddDays((int) (6 - lastDayInMonth.DayOfWeek));
return new DateTime[] { firstDayInView, lastDayInView };
}
DateTime[] monthDisplayLimits = GetMonthDisplayLimits(2014, 8);
var firstDayInView = monthDisplayLimits[0];
var lastDayInView = monthDisplayLimits[1];
Since "DayOfWeek" is a value between 0 and 6, this approach rounds down the first weekday and rounds up the last weekday.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to add days to a date in Java
Consider the date to be 19/05/2013 and the number to be 14. I would like to get the resulting date after adding the number to the month.
Expected result is: 19/07/2014.
In .NET you could do use the AddMonths method:
DateTime date = new DateTime(2013, 5, 19);
DateTime newDate = date.AddMonths(14);
As far as parsing a date from a string using a specified format you could use the TryParseExact method:
string dateStr = "19/05/2013";
DateTime date;
if (DateTime.TryParseExact(dateStr, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
// successfully parsed the string into a DateTime instance =>
// here we could add the desired number of months to it and construct
// a new DateTime
DateTime newDate = date.AddMonths(14);
}
else
{
// parsing failed => the specified string was not in the correct format
// you could inform the user about that here
}
You can DateTime.AddMonths to add months.
DateTime date = new DateTime(2013, 5, 19);
DateTime newDate = date.AddMonths(14);
In Java:
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // today is the default
c.add(Calendar.DATE, 1); // number of days to add (1)
c.getTime(); // The new date
Just use AddMonths to add the specified number of months to the value of this instance.
DateTime date = new DateTime(2013, 5, 19); // (yyyy,MM,dd)
DateTime dt = date.AddMonths(14);