How to get from datetimepicker only the separated values of the date? - c#

How do I get from datetimepicker only the separated values of the date?
For example, for this date (6,5,2017) I want to get--> day=5 , month=6, year=2017.

DateTimePicker value is type DateTime which has properties day, month, year.
To access them:
dateTimePicker1.Value.Day;
dateTimePicker1.Value.Month;
dateTimePicker1.Value.Year;
These properties are read only. To modify it use methods:
Edit (thx to #Richard): AddDays, AddMonths, AddYears methods return new DateTime value that you have to assign back to DateTimePicker.Value
dateTimePicker1.Value = dateTimePicker1.Value.AddDays(_days);
dateTimePicker1.Value = dateTimePicker1.Value.AddMonths(_months);
dateTimePicker1.Value = dateTimePicker1.Value.AddYears(_years);

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# Sum to DateTime.Now.TimeOfDay; [duplicate]

I have a calendar and a textbox that contains a time of day. I want to create a datetime that is the combination of the two. I know I can do it by looking at the hours and mintues and then adding these to the calendar DateTime, but this seems rather messy.
Is there a better way?
You can use the DateTime.Add() method to add the time to the date.
DateTime date = DateTime.Now;
TimeSpan time = new TimeSpan(36, 0, 0, 0);
DateTime combined = date.Add(time);
Console.WriteLine("{0:dddd}", combined);
You can also create your timespan by parsing a String, if that is what you need to do.
Alternatively, you could look at using other controls. You didn't mention if you are using winforms, wpf or asp.net, but there are various date and time picker controls that support selection of both date and time.
If you are using two DateTime objects, one to store the date the other the time, you could do the following:
var date = new DateTime(2016,6,28);
var time = new DateTime(1,1,1,13,13,13);
var combinedDateTime = date.AddTicks(time.TimeOfDay.Ticks);
An example of this can be found here
Depending on how you format (and validate!) the date entered in the textbox, you can do this:
TimeSpan time;
if (TimeSpan.TryParse(textboxTime.Text, out time))
{
// calendarDate is the DateTime value of the calendar control
calendarDate = calendarDate.Add(time);
}
else
{
// notify user about wrong date format
}
Note that TimeSpan.TryParse expects the string to be in the 'hh:mm' format (optional seconds).
Using https://github.com/FluentDateTime/FluentDateTime
DateTime dateTime = DateTime.Now;
DateTime combined = dateTime + 36.Hours();
Console.WriteLine(combined);
DateTime newDateTime = dtReceived.Value.Date.Add(TimeSpan.Parse(dtReceivedTime.Value.ToShortTimeString()));
Combine both. The Date-Time-Picker does support picking time, too.
You just have to change the Format-Property and maybe the CustomFormat-Property.

Format text in a Masked TextBox

I have a masked text box that is used to show today's date, like this:
txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
However it can still be edited to change the date. Being a masked text box, the only worry is if someone wants to add the date like so:
27/1/15
Is there a way I can edit this to add the additional information and automatically format it to this? Possibly using String.Format perhaps?
27/01/2015
EDIT: To clarify, When the form opens, the txtDate will automatically receive today's date, but if a user wants to change the date, how can I ensure that the date will remain in the right format? I.e. dd/MM/yyyy.
try something like this
DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000}", d.Month, d.Day, d.Year);
Edit:
You can add days, months, years... to your variable of type DateTime d
Example:
d = DateTime.Now;
d = d.AddDays(5); // add 5 days to current date
EDIT2
Say you have 3 textBoxes txtDays, txtMonth and txtYear
int year = Convert.ToInt32(txtYear.Text);
int month = Convert.ToInt32(txtMonth.Text);
int days = Convert.ToInt32(txtDays.Text);
// you can assign any date as follows:
DateTime d = new DateTime(year, month, days);
Or if the users will have only one textBox called txtDate and they have to enter the date in the form "MM/dd/yyyy":
var[] date = txtDate.Split('/');
txtDate.Text = String.Format("{0:00}/{1:00}/{2:0000}", date[0], date[1], date[2]);

how can i assign only year say 2011 in a datetime variable in c#

I have a asp Text box as
where the user will fill only a year value, For this value I have Datetime type Property in c# application and Date type column in DB. So I want to convert that txtYear.Text to DateTime But it will only hold and/or show the year. Please help me in this situation.
A DateTime object will always hold a complete DateTime value, you can't use it to store a year only. (what use would that be anyway?) Besides, the datatype of a "year" is int, not DateTime.
So, I'd like to suggest changing your property to datatype int, both in your code and database.
To display just the year use the format "yyyy".
string s = "2011";
DateTime d = new DateTime(int.Parse(s), 1, 1);
Console.WriteLine(d.ToString("yyyy"));
Console.WriteLine(d);
You have to specify the format of the DateTime value you are manipulating:
String dateTimeFormat = "yyyy";
To show only a part of the DateTime value use the following:
dateTimeValue.ToString(dateTimeFormat);
To read a String value that represents a year into a DateTime use the following:
DateTime.ParseExact(stringValue, dateTimeFormat, CultureInfo.InvariantCulture);
DateTime.ParseExact Method (String, String, IFormatProvider) converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
DateTime.ToString Method converts the value of the current DateTime object to its equivalent string representation.
Rather than applying any string manipulating function make use of Year property. Check the documentation on the msdn by visiting below link.
DateTime.Year Property
A DateTime always has a full date component. When you create the DateTime instance, you'll need to assign a month and day, but you can ignore them in your usage.
DateTime d = new DateTime(int.Parse(txtYear.Text, 1, 1);
txtYear.Text = d.ToString("yyyy");
Even better would be not to use a DateTime but just use int. If you have only a year, you only need an int.
i assume the text box name is txYear
DateTime dt = new DateTime (Convert.ToInt32(txYear.text),1,1)
save this dt value in database
If you want only the year, why don't you make it of type smallint?
Anyway if you do really want to make it an year,
DateTime x = new DateTime(Convert.ToInt32(txtYear.text), 1, 1);
But make sure you validate that txtYear.text actually does have a valid year.
That is how I did and it worked.
string format = "yyyy";
var CurrentYear = DateTime.Now.ToString(format);

DateTime convert to Date and then back to DateTime in C#

I use this to convert DateTime value into Date and then I add 00:00:00 and 23:59:59 to make sure whole day is taken into consideration when counting stuff. I'm pretty sure it's wrong way of doing things. What would be the right way?
DateTime varObliczOd = DateTime.Parse(dateTimeWycenaPortfelaObliczDataOd.Value.ToShortDateString() + " 00:00:00");
DateTime varObliczDo = DateTime.Parse(dateTimeWycenaPortfelaObliczDataDo.Value.ToShortDateString() + " 23:59:59");
if dateTimeWycenaPortfelaObliczDataOd is of type DateTime, You can use:
dateTimeWycenaPortfelaObliczDataOd.Date
to get the date part only (time will be 00:00:00...).
If you want to get the very last tick of the date, you can use:
dateTimeWycenaPortfelaObliczDataOd.Date.AddDays(1).AddTicks(-1)
but you really better work with the next date (.AddDays(1)).
In any case, there is no need to convert to string and back to DateTime.
DateTime objects have a Date property which might be what you need.
You can use the following properties / methods on a DateTime object to get your values :
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Date;
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataOd.AddDayes(1).AddTicks(-1);
It would help to know why you're needing it, but this would work.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Date;
DateTime varObliczDo = varObliczOd.AddDays(1).AddSeconds(-1);
Using the Date attribute and then manipulating them directly to create the required time component - no need to bother with parsing and conversion.
You could use the Date property of the DateTime object to accomplish what you need.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Value.Date;
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataDo.Value.Date.AddDays(1);
If you really want it to end at 23:59:59 you can do:
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataDo.Value.Date.AddDays(1).AddSeconds(-1);
Will set varObliczDo to be your ending date with no time plus one day (at midnight). So if dateTimeWycenaPortfelaObliczDataDo was 2010-03-05 16:12:12 it would now be 2010-03-06 00:00:00.
Something like this maybe? I've typed this out of my head, there are probably some mistakes in the code.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.AddSeconds(-dateTimeWycenaPortfelaObliczDataOd.Seconds).AddMinutes(-dateTimeWycenaPortfelaObliczDataOd.Minutes).AddHours(-dateTimeWycenaPortfelaObliczDataOd.Hours);
DateTime varObliczDo = new DateTime(dateTimeWycenaPortfelaObliczDataDo.Year, dateTimeWycenaPortfelaObliczDataDo.Month, dateTimeWycenaPortfelaObliczDataDoDay, 23, 59, 59);
DateTime newDate = new DateTime( oldDate.Year, oldDate.Month, oldDate.Day, 23, 59,59 )
DateTime newDate = new DateTime( oldDate.Year, oldDate.Month, oldDate.Day, 0, 0, 0 )
You could work with TimeSpan:
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd - new TimeSpan(dateTimeWycenaPortfelaObliczDataOd.Hours, dateTimeWycenaPortfelaObliczDataOd.Minutes, dateTimeWycenaPortfelaObliczDataOd.Seconds);
Like that you avoid at least the parsing, which can fail depending on the local culture settings.

Categories

Resources