Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
User can input any date, month and year like 12/12/2013, 1/1/2014, 7/5/2014, 5/1/2012 in MM\DD\YYYY format.
How to check the date is first date of month ?
If the user entry is not first date of month, I want to modify that entry to 1st date of month. In my Examples, I want
12/12/2013 as 12/1/2013
1/1/2014 as 1/1/2014(No Change)
7/5/2014 as 7/1/2014
5/1/2012 as 5/1/2012(No Change)
Thanks
DateTime date = ... // your original date here...
// Don't bother checking, just create a new date for the 1st.
date = new DateTime(date.Year, date.Month, 1);
UPDATE:
The OP has apparently changed the specs:
DateTime date = ... // your original date here...
if (date.Day != 1)
date = new DateTime(date.Year, date.Month, 1).AddMonths(1);
(let the .AddMonths() method worry about the year rolling over in December...)
IMO, since you have a definite format you expect from users (MM\DD\YYYY) why not do a simple split and dig your hit:
string arbitDate = "4/3/2014";
string UsersFirstDay = arbitDate.Trim().Split(new String[] { "/" }, StringSplitOptions.RemoveEmptyEntries)[1].Trim();//index 1 is the DD part - according to your format
UsersFirstDay = (UsersFirstDay == "1") ? UsersFirstDay : "1";
Pass your date to this function:
public static void ConvertToFirstDate(ref DateTime dt){
TimeSpan ts = dt.Subtract(new DateTime(dt.Year, dt.Month, 1));
dt = dt.AddDays(-ts.Days);
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How do i go about creating a datetime based on only the following information:
Day of Week, Hour & Minuet.
I.e. I don't care what month it is or even what the date is (i don't have that info in the database).
I thought i could parse them as a string but is turning out to be more difficult than i thought.
Created on function for you it might be helpful to you ..
public DateTime CreateDayOfWeek(int DayOfWeek,int hour,int min)
{
DateTime dt = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,hour,min,0);
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysUntilTuesday = (DayOfWeek - (int)dt.DayOfWeek + 7) % 7;
// DateTime nextTuesday = today.AddDays(daysUntilTuesday);
dt = dt.AddDays(daysUntilTuesday);
return dt;
}
I have tested for several dates and its working for me ..
let me know if you have any issue ..
Here is .netFiddle
You can create your date like this...
var hour = 1; // you set this from code
var minute = 1; // set this from code
var now = DateTime.Now;
var tempDateTime = new DateTime(now.Year, now.Month, now.Day, hour, minute, 0);
// Make this enum whatever you want your date to be...
var num = (int)DayOfWeek.Sunday;
var dateForComparison = tempDateTime.AddDays(num - (int)tempDateTime.DayOfWeek);
Now dateForComparison holds a date that has your time values set and the day of week you have specified.
You said you don't care about what month or date it is, which makes me assume you want any date as long as it is the right day of week and time (hour and minute). You can do it like this:
var date = new System.DateTime(2016, 9, 25);
date = date.AddDays(dow).AddHours(hours).AddMinutes(minutes);
September 25, 2016 was a Sunday. Add the day of the week (Sunday = 0) and you get the correct day. Then add the hours and minutes. Of course, if you like you can pick any Sunday of any month/year to start.
You can create a function for build your date:
public DateTime BuildDate(Int32 day, Int32 hour, Int32 minute)
{
var now = DateTime.Now;
var initialDate = now.AddDays(((Int32)now.DayOfWeek + 1) * -1);
return new DateTime(initialDate.Year, initialDate.Month, initialDate.AddDays(day).Day, hour, minute, 0);
}
The day of week is start from sunday in this case.
You can use: DateTime.ToString Method (String)
DateTime.Now.ToString("ddd HH:mm") // for military time (24 hour clock)
More: https://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have string time. lets say '06:35 PM'. I want to convert the string to DateTime.
The date must be current time(the day as they input the time).
I did
string times = endTime;
DateTime dt;
(DateTime.TryParseExact(times, "YYYY-MM-dd HH:mm tt", CultureInfo.InvariantCulture,DateTimeStyles.None, out dt))
But it didn't works. it make a null value. because when I try to put the result on label, the label did not show anything. and also I have been try
var date = DateTime.Parse("06:45 AM");
Console.WriteLine(date);
But it didn't works too and it makes an error.
ERROR System.Data.SqlClient.SqlException (0x80131904): The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. The statement has been terminated. "
How do I convert it ?
I think you are passing the string "06:45 AM" to the database and this is not a valid entry since the DB does not know how to store it, hence the exception.
Looking a bit further, in your first example, YYYY should be lowercase yyyy. YYYY will not parse properly correctly in to a date format.
Considering the second example you have two options:
1) When writing to the database, make sure you pass a valid date, e.g. below. You may need to try a few formats to match up to what your DB expects but it will need a full date and time.
var date = string.Format("{0:yyyy-MM-dd HH:mm tt}", DateTime.Parse("06:45 AM"));
Console.WriteLine(date);
2) Use a full DateTime approach using the correct SQL parameter type. This looks like a good explanation covering a few gotchas. Using DateTime in a SqlParameter for Stored Procedure, format error
If day doesn't matter, you can use following
DateTime date;
if (DateTime.TryParseExact("06:45 AM", new[] {"h:mm tt"}, null, DateTimeStyles.None, out date))
{
Console.WriteLine(date);
Console.WriteLine(date.TimeOfDay);
}
I think the below code will solve your issue;
DateTime dt = DateTime.Now;
TimeSpan ts = new TimeSpan(06, 45, 0);
dt = dt.Date + ts;
To convert string to DateTime format, use the below code;
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);
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.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
addition of two month and year in asp.net with c#.
if i select any one Month/year: like march/2014 and add(+) 12 month,
so it should be give the February/2014.
In this we can see Loan Period is: 12 (month) and below we can see loan start from month: 07(july/2014) so end of the load should be 06/2015. and the both month are in textbox it means they are string.
DateTime dt = new DateTime(2013, 1, 1);
dt.AddYear(1);
dt.AddMonths(2);
//Date is 2014, 3 (March), 1
Alternatively if you wish to substrat years and months you can use:
dt.AddYear(-1);
dt.AddMonths(-1);
//Date is 2013, 2 (February),1
Here you will not get 02/2015 if you add 12 months in 03/2014. You will get 03/2015 in result as shown below.
var inputString = "march/2014";
DateTime dt = DateTime.ParseExact(inputString, "MMMM/yyyy", CultureInfo.InvariantCulture);
var result = dt.AddMonths(12).ToString("MMMM/yyyy");
Will result in => "march/2015"
It seems that yous should add -1, not 12 months (if you want to get February from March):
String fromDate = "march/2013";
// result == "February/2013"
String result = DateTime
.ParseExact(fromDate, "MMMM/yyyy", CultureInfo.InvariantCulture)
.AddMonths(-1)
.ToString("MMMM/yyyy", CultureInfo.InvariantCulture);
In case that you want to add a year and two months (and so your example is incorrect)
String fromDate = "march/2013";
// result == "May/2014"
String result = DateTime
.ParseExact(fromDate, "MMMM/yyyy", CultureInfo.InvariantCulture)
.AddYears(1)
.AddMonths(2)
.ToString("MMMM/yyyy", CultureInfo.InvariantCulture);
I need to get the previous months date in asp.net which means that if the current date is 5/2/2013 then I want to display the previous date as 5/1/2013. How to solve this?
Try this :
DateTime d = DateTime.Now;
d = d.AddMonths(-1);
The solution is to substract 1 month:
DateTime.Now.AddMonths(-1)
Or if not just build the datetime object from scratch:
var previousDate = DateTime.Now.AddMonth(-1);
var date = new DateTime(previousDate.Year, previousDate.Month, DateTime.Now.Day);
this time you are guaranteed that the year and month are correct and the day stays the same. (although this is not a safe algorithm due to cases like the 30th of march and the previous date should be 28/29th of February, so better go with the first sugeestion of substracting a month)
If you already have date time in string format
var strDate = "5/1/2013";
var dateTime = DateTime.ParseExact(strDate,
"dd/MM/yyyy",
CultureInfo.InvariantCulture);
var lastMonthDateTime = dateTime.AddMonths(-1);
else if you have DateTime object just call it's AddMonths(-1) method.