How to change "ddd" datetime format to a number view - c#

I want to make that code to show me a current datetime on my pc clock when i click a button... i did it with that code listed down. But here is my question how can i make the "ddd" (day of a week) to be shown in number, not in words, I mean:
00-sunday
01-monday
and etc. ...
This is my code for the button:
private void SetClock_Click(object sender, EventArgs e)
{
SetClock.Click += new EventHandler(SetClock_Click);
{
DateTime time = DateTime.Now;
string format = "yy-MM-dd-ddd-hh-mm-ss";
txtSend.Text = time.ToString(format);
}
}
What i have to add to make it. Thanks

txtSend.Text = string.Format("{0:yy-MM-dd}-{1:00}-{0:hh-mm-ss}", time, (int)time.DayOfWeek);

A format isn't required, you can just cast DayOfWeek to an int:
var dayAsInt = (int)DateTime.Now.DayOfWeek;
Looking at the Custom Date and Time Format Strings page, there doesn't appear to be a format string for it :-(

The following should do it:
txtSend.Text =
time.ToString("yy-MM-dd-") +
((int)time.DayOfWeek).ToString("00") +
time.ToString("-hh-mm-ss");

You could use this to get the day of week numeric
int dayofweek = (int)DateTime.Now.DayOfWeek;

Related

Getting first and last date of selected month c# winforms

before getting started I want to tell that I already know how to select the 1st and last date of the current month. But, my question is different, I want to select the 1st and the last date of the selected month using date-time picker in c# winforms.
public Form1()
{
InitializeComponent();
MonthYearDT();
}
private string MonthYearDT()
{
dTMY.Format = DateTimePickerFormat.Custom;
dTMY.CustomFormat = "yyyy-MM-dd";
dTMY.ShowUpDown = true; // to prevent the calendar from being displayed
return dTMY.Value.ToString("yyyy-MM-dd");
}
private void BtnExecute_Click(object sender, EventArgs e)
{
.
.
.
.
monthYear = MonthYearDT();
.
.
.
}
In the above, the value of monthYear is 2019-12-19. It can be changed to any month. I want to get the 1st 2019-12-01 and last date 2019-12-31 of the selected month.
How can I do this?
Any help would be highly appreciated.
Before doing anything firstly change the function MonthYearDT() from string to DateTime
private DateTime MonthYearDT()
{
dTMY.Format = DateTimePickerFormat.Custom;
dTMY.CustomFormat = "yyyy-MM";
dTMY.ShowUpDown = true; // to prevent the calendar from being displayed
dTMY.Enabled = false;
return dTMY.Value;
}
Getting the first is easy. Just create a new DateTime like so
DateTime selectedDate = MonthYearDT();
var first = new DateTime(selectedDate.Year, selectedDate.Month, 1);
getting the second is just as easy. Use first, add one month and subtract one day like so
var second = first.AddMonths(1).AddDays(-1);
firstDate = first.ToString("yyyy-MM-dd");
lastDate = second.ToString("yyyy-MM-dd");
Universal truth is that the first day of any month would always be same.
And to get the last date below DateTime function can be used. You need year also along the month to get the last day
var lastDay = DateTime.DaysInMonth(year, month);
var lastDayDate = new DateTime(year, month, lastDay);

how to work with double in textbox?

I would like to write a code that reads a time the user wrote into textbox1, lets say 09:00 (hh:mm), save it into a variable, then takes this variable and adds 08:40 to it and Outputs then the outcome 17:40 into textbox2.
The Problem is, when working with double it is working well, but I need to use the hh:mm - Format, I know some languages have the Option to declare a variable as time but it seems like c# isnt doing this. so whats the solution?
thats my current code
void CmdWriteClick(object sender, EventArgs e)
{
string varstr = textbox_1.Text;
double muss = 8.40;
double vardb = Convert.ToDouble(varstr);
double end = vardb + muss;
textbox_2.Text = end.ToString();
}
this would of course Output me double-numbers. so if varstr is 08.30 it would Output 16,7 when I Need to make it Output 17:10. Any help is appreciated
thank you guys
You shouldn't be using a TextBox for this. You have a specific control to take care of dates and times: DateTimePicker.
Add one of these to your form. If you only want the user to modify the time, disallowing date changes, you can do the following:
public myForm()
{
InitializeComponent();
....
myDateTimePicker.Format = DateTimePickerFormat.Custom;
myDateTimePicker.CustomFormat = "HH:mm"; //Shows only hours and minutes in 24h format
myDateTimePicker.Value = DateTime.Now.Date; //sets the time to today at 0:00
myDateTimePicker.MinDate = DateTime.Now.Date;
myDateTimePicker.MaxDate = DateTime.Now.Date.Add(new TimeSpan(23, 59, 59)); //User can't change date.
}
private DateTime newTime;
private void myDateTimePicker_ValueChanged(object sender, EventArgs e)
{
newTime = myDateTimePicker.Value.AddHours(8.5);
}
Obviously if you want the user to set the date too, then simply change the MinValue and MaxValue restrictions to your requirements (if any) and choose one of the predefined format options instead of DateTimePickerFormat.Custom.
Try this :
dateValue.AddHours(8);
dateValue.AddMinutes(30);
You can use DateTime instead of double.
private void button1_Click(object sender, EventArgs e)
{
DateTime dateTime = DateTime.ParseExact(textBox1.Text, "HH:mm", System.Globalization.CultureInfo.CurrentCulture);
TimeSpan time = new TimeSpan(8,40,0);
DateTime outputTime = dateTime.Add(time);
textBox2.Text = outputTime.ToString("HH:mm");
}
You could do something like this:
string input = textbox_1.Text;
DateTime inputTime;
if (DateTime.TryParseExact(input, "HH:mm", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out inputTime))
{
DateTime outputTime=inputTime.AddHours(8).AddMinutes(40);
textbox_2.Text = outputTime.ToString("HH:mm");
}
Basically, you parse the input string to a DateTime variable, add the time you need and then convert back to string to show it in your TextBox
If you really want to do it with double, you have to think about the conversion from minutes to whole numbers. 8.4 would be then 60 * .4 = 24 minutes.
For the rest, the text string you can parse using TimeSpan.Parse and you can write a custom function that would parse the double to a TimeSpan and then simply add the 2 together, like so:
using System;
namespace TimeParser {
class Program {
static TimeSpan GetTimeFromText( string text ) {
if ( string.IsNullOrWhiteSpace( text ) ) {
return TimeSpan.Zero;
}
return TimeSpan.Parse( text );
}
static TimeSpan GetTimeFromDouble( double value ) {
if ( value <= 0 ) {
return TimeSpan.Zero;
}
int hours = (int)Math.Floor( value );
int minutes = (int)(( value - hours )*60);
return new TimeSpan(0, hours, minutes, 0);
}
static TimeSpan GetAddedTime( string input, double time ) {
var textTime = GetTimeFromText( input );
return textTime.Add( GetTimeFromDouble( time ) );
}
static void Main( string[] args ) {
var totalTime = GetAddedTime( "8:30", 8.67 );
Console.WriteLine( totalTime ); // 17.10
}
}
}

Using DateTime With input from a textbox.text

I have this code that when executed gives me 74 Days, which is correct, but the date for oldDate has to come from a TextBox. Does anyone know how to do this as the DateTime only takes three integers.
private void myButton_Click(object sender, RoutedEventArgs e)
{
string myDate = myTextBox.Text;
DateTime oldDate = new DateTime(2013, 6, 5);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = oldDate - newDate;
// Difference in days.
int differenceInDays = ts.Days;
differenceInDays = ts.Days;
myTextBlock.Text = differenceInDays.ToString();
}
You can parse the date from the user:
string myDate = myTextBox.Text;
DateTime oldDate;
if (!DateTime.TryParse(myDate, out oldDate))
{
// User entered invalid date - handle this
}
// oldDate is set now
That being said, depending on the UI framework, a more appropriate control (ie: the DateTimePicker from the extended WPF toolkit, etc) may be easier to use.
From your code you have to obtain oldDate from myTextBox, which you have stored in myDate string variable. You can convert it to datetime
oldDate=Convert.ToDateTime(myDate);
But since it might cause exception use following
`DateTime myyDateTime;if(DateTime.TryParse(myDate, out myDateTime){//use your date difference code here}

How to delete data from selected Date to current Date using DateTimePicker

My problem is to delete data from given date to current date,
My code works fine for deleting the data by the date given in the DateTimePicker.
i want to delete the data from given date in DateTimePicker to CurrentDate.
For example:
In subfolder123 the data is available from 20100131 to 20110531 (Date Format yyyyMMdd).
I want to delete the date from 20100215 to 20110531.
Hope you understood my Question and problem.
Is there any suggestions?
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
string todaysDate = dateTimePicker1.Text;
int FinalDate4 = 0;
string Destinationnsefx = "C:\\folder\\subfolder\\subfolder123";
int xyz = 0;
string SecSym = (9722).ToString();
MWriterClass writerdelete1 = new MWriterClass();
try
{
writerdelete1.OpenDirectory(Destinationnsefx);
writerdelete1.OpenSecurityBySymbol(SecSym);
FinalDate4 = int.Parse(todaysDate);
if (writerdelete1.get_bDateExists(FinalDate4))
{
try
{
writerdelete1.DeleteIntradaySecRecordEx(FinalDate4, 080000, 240000);
}
catch
{
}
}
writerdelete1.CloseSecurity();
writerdelete1.CloseDirectory();
}
catch
{
}
}
Thanks in advance.
It sounds like you get a date from your DateTime picker and you need to work from that start date to your end date, correct?
In that case, look at the AddDays method for a DateTime object.
For example, this snippet of code will start at 4/1/2011 and print every date from then until today, in the format you specified.
var workingDate = new DateTime(2011, 4, 1);
while (workingDate < DateTime.Today)
{
workingDate = workingDate.AddDays(1);
Console.WriteLine(string.Format("{0:yyyyMMdd}", workingDate));
}

How to get the selected date of a MonthCalendar control in C#

How to get the selected date of a MonthCalendar control in C# (Window forms)
"Just set the MaxSelectionCount to 1 so that users cannot select more than one day. Then in the SelectionRange.Start.ToString(). There is nothing available to show the selection of only one day." - Justin Etheredge
From here.
I just noticed that if you do:
monthCalendar1.SelectionRange.Start.ToShortDateString()
you will get only the date (e.g. 1/25/2014) from a MonthCalendar control.
It's opposite to:
monthCalendar1.SelectionRange.Start.ToString()
//The OUTPUT will be (e.g. 1/25/2014 12:00:00 AM)
Because these MonthCalendar properties are of type DateTime. See the msdn and the methods available to convert to a String representation. Also this may help to convert from a String to a DateTime object where applicable.
Using SelectionRange you will get the Start and End date.
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
var startDate = monthCalendar1.SelectionRange.Start.ToString("dd MMM yyyy");
var endDate = monthCalendar1.SelectionRange.End.ToString("dd MMM yyyy");
}
If you want to update the maximum number of days that can be selected, then set MaxSelectionCount property. The default is 7.
// Only allow 21 days to be selected at the same time.
monthCalendar1.MaxSelectionCount = 21;
For those who are still trying, this link helped me out, too; it just puts it all together:
http://dotnetslackers.com/VB_NET/re-36138_How_To_Get_Selected_Date_from_MonthCalendar_control.aspx
private void MonthCalendar1_DateChanged(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
//Display the dates for selected range
Label1.Text = "Dates Selected from :" + (MonthCalendar1.SelectionRange.Start() + " to " + MonthCalendar1.SelectionRange.End);
//To display single selected of date
//MonthCalendar1.MaxSelectionCount = 1;
//To display single selected of date use MonthCalendar1.SelectionRange.Start/ MonthCalendarSelectionRange.End
Label2.Text = "Date Selected :" + MonthCalendar1.SelectionRange.Start;
}
It'll be helpful if you want just to convert it by:
String myCalendar = monthCalendar1.SelectionRange.Start.ToShortDateString()
But if you want to get a formatted output you could instead:
String myCalendar = monthCalendar1.SelectionRange.Start.ToString("yyyy-MM-dd")
It's important to use year and day as lower caps, and month as upper or else it'll return you a wrong format, for example, if you do:
String myCalendar = monthCalendar1.SelectionRange.Start.ToString("YYYY-MM-DD")
it will return: YYYY-07-DD (If the original date's month was July)
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
string clickeddate = monthCalendar1.SelectionRange.Start.ToString("dddd, dd MMM yyyy");
richTextBox.AppendText(clickeddate); //or whatever you decide to do with it.
}
SelectionRange property

Categories