I have two DatePickers in my app. First, shows the FromDate which is CurrentDate+1, the second shows the ToDate ie. FromDate+1.
I have got the above scenario working. But now I want to disable all the dates after 6 months from the FromDate.
I tried doing the following,but the calender then shows 01/01/1970 as the current date.
BookingActivity.cs
void IbtnToDate_Click(object sender, EventArgs e)
{
toDateClicked = true;
fromDateClicked = false;
dateFragment = new DatePickerFragment(this, DateTime.Parse (editFromDate.Text.ToString ()).AddDays (1), this, DateTime.Parse (editFromDate.Text.ToString ()));
dateFragment.Show(FragmentManager, null);
}
void IbtnFromDate_Click(object sender, EventArgs e)
{
fromDateClicked = true;
toDateClicked = false;
dateFragment = new DatePickerFragment(this, date.AddDays (1), this, date.AddDays (1));
dateFragment.Show(FragmentManager, null);
}
public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
var date1 = new DateTime(year, monthOfYear + 1, dayOfMonth);
if (fromDateClicked)
UpdateFromDate (date1);
else if (toDateClicked) {
UpdateToDate (date1);
}
}
DatePickerFragment.cs
public class DatePickerFragment : DialogFragment
{
private readonly Context _context;
private DateTime _date, _minDate, _maxDate;
private readonly Android.App.DatePickerDialog.IOnDateSetListener _listener;
public DatePickerFragment(Context context, DateTime date, Android.App.DatePickerDialog.IOnDateSetListener listener, DateTime minDate)
{
_context = context;
_date = date;
_listener = listener;
_minDate = minDate;
}
public override Dialog OnCreateDialog(Bundle savedState)
{
var dialog = new Android.App.DatePickerDialog(_context, _listener, _date.Year, _date.Month - 1, _date.Day);
dialog.DatePicker.MinDate =_minDate.AddDays (1).Millisecond;
dialog.DatePicker.MaxDate = _date.AddMonths(6).Millisecond;
return dialog;
}
}
How can I achieve it? Any help would be appreciated.
You can use setMaxDate and can do something like:
1- Get the date from _mindate string:
String dateString = "03/26/2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2- Get date of 6 months from min_date:
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(convertedDate);
cal.add(Calendar.MONTH, 1);
Date 6MonthsFromCurrentDate = cal.getTime();
3- Restricting the datePicker to that date:
datePickerDialog.getDatePicker().setMaxDate(6MonthsFromCurrentDate.getTime());
Use these lines of code.
Calendar ci = Calendar.getInstance();
String CiDateTime = ci.get(Calendar.YEAR) + "-" +
(ci.get(Calendar.MONTH) + 7) + "-" + //for 6 month future
ci.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
Date d;
try {
d = f.parse(CiDateTime);
long milliseconds = d.getTime();
_date.setMaxDate(milliseconds);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
I want to clear the DateTimePicker control value when i click on clear button but i can't do that with simple double qoutes, So please help me
tbAddress.Text = "";
dtpBirth.Value = "";
cBoxGender.SelectedIndex = -1;
This should do the trick
dtpBirth.CustomFormat = " ";
dtpBirth.Format = DateTimePickerFormat.Custom;
it will clear the input box.
try is
dateTimePickerDOB.Value = DateTimePicker.MinimumDateTime
in this your date and time going to be minimum date and time in your DateTimePicker and dateTimePickerDOB mean your Design(name)
or
try this for clear the date
dateTimePicker_dob.Text = string.Empty;
in here dateTimePickerDOB mean your Design(name)
The DateTimePicker.Value is from type DateTime and not a String.
dtpBirth.Value = DateTime.Now;
You can do this:
private void DateTimePicker1_ValueChanged(object sender, EventArgs e)
{
if (dateTimePicker1.Value == DateTimePicker.MinimumDateTime)
{
dateTimePicker1.Value = DateTime.Now; // This is required in order to show current month/year when user reopens the date popup.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " ";
}
else
{
dateTimePicker1.Format = DateTimePickerFormat.Short;
}
}
private void Clear_Click(object sender, EventArgs e)
{
dateTimePicker1.Value = DateTimePicker.MinimumDateTime;
}
Input string was not in a correct format.
I have use uniqueidentifier as my id in sql server database error is showing in the first line where ID = ...
private void DataGridViewDischarge_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
ID = Convert.ToInt32(DataGridViewDischarge.Rows[e.RowIndex].Cells[0].Value.ToString());
TxtHeadOverNotch.Text = DataGridViewDischarge.Rows[e.RowIndex].Cells[1].Value.ToString();
TxtDischargeQ.Text = DataGridViewDischarge.Rows[e.RowIndex].Cells[2].Value.ToString();
}
Unique Identifier is GUID in sql server and GUID cannot be represent as int so you have to parse it to GUID, see here:
Guid id = Guid.Parse(DataGridViewDischarge.Rows[e.RowIndex].Cells[0].Value.ToString());
private void dgv_expenditure_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
DataGridViewRow dgv = dgv_expenditure.Rows[e.RowIndex];
int id = Convert.ToInt32(dgv.Cells[0].Value);
tabControl1.SelectedIndex = 1;
loadform(id);
}
private void loadform(int id)
{
// throw new NotImplementedException();
SanmolCAEntities1 _db = new SanmolCAEntities1();
var u = _db.a_expenditure.Where(p => p.id == id).FirstOrDefault();
txt_name.Text = u.name;
txt_CreateBy.Text = u.createby;
dateTimePicker_excrdate.Value.ToString("yyyy-MM-dd HH:mm:ss");
txt_updateBy.Text = u.updateby;
dateTimePicker_exupdate.Value.ToString("yyyy-MM-dd HH:mm:ss");
}
error in this line:
int id = Convert.ToInt32(dgv.Cells[0].Value);
this is error;
input string was not in a correct format
I am making a NetcafeProgram in C# and I want to get the current DateTime. I want my output like this (hr.mins)"0.25". I have the current DateTime but I want to show it like this (hr.mins)"0.25" in the labelTime_1 but it is not working. This is the command which I used
starttime_1 = DateTime.Now.ToString("h:mm:ss tt");
and I changed it to
starttime_1 = DateTime.Now.ToString("h.mm");
and then I wanted to get the duration like this
TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
but it gives me errors.
Here is a Screenshot of My Formv:
I want the time to get posted On that Time Elapsed Label but it doesn't work. Here is the coding of BtnStop1
private void btnStop_1_Click(object sender, EventArgs e)
{
//string duration = Convert.ToInt32(((starttime_1) - (endtime_1)));
gbx_1.BackColor = Color.LimeGreen;
btnStop_1.Enabled = false;
//endtime_1 = DateTime.Now.ToString("h:mm:ss tt");
//TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
endtime_1 = DateTime.Now.ToString("h.mm tt");
TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
lblTime_1.Text = Convert.ToString(duration);
string var = "Cabin One is Free";
btnStart_1.Enabled = true;
HP_1.Enabled = true;
CR_1.Enabled = true;
reader = new SpeechSynthesizer();
reader.SpeakAsync(var);
}
Coding of BtnStart
private void btnStart_1_Click(object sender, EventArgs e)
{
gbx_1.BackColor = Color.Red;
btnStart_1.Enabled = false;
//starttime_1 = DateTime.Now.ToString("h:mm:ss tt");
starttime_1 = DateTime.Now.ToString("h.mm tt");
lblTime_1.Text = "CountingTime";
string var = "Cabin One is Occupied";
reader = new SpeechSynthesizer();
reader.SpeakAsync(var);
HP_1.Enabled = false;
CR_1.Enabled = false;
}
Here Are My Variables
public string starttime_1;
public string starttime_2;
public string starttime_3;
public string starttime_4;
public string starttime_5;
public string starttime_6;
public string endtime_1;
public string endtime_2;
public string endtime_3;
public string endtime_4;
public string endtime_5;
public string endtime_6;
I would strongly suggest changing your variable types to DateTime?. It is better to store data in its native type and then do the convert to string on display. This way, when you want the duration, you are not parsing back to DateTime. You can handle any rounding you want on the base data.
So, your conversion to string should be at the highest level of you stack. It will keep your code cleaner and make it easier to refactor the logic away from the UI later if appropriate.
Not really sure I understand all this parsing but if you're just trying to record start and stop times and output a timespan I would do as Jon Skeet recommend with the stopwatch. Something along these lines looks like what you're going for but a bit cleaner.
// Build stopwatch and lists
Stopwatch sw = new Stopwatch();
List<string> startTimes = new List<string>();
List<string> endTimes = new List<string>();
private void startBtn_Click(object sender, EventArgs e)
{
// Start stopwatch and record start time
sw.Start();
startTimes.Add(DateTime.Now.ToString("h.mm"));
}
private void stopBtn_Click(object sender, EventArgs e)
{
// Stop stopwatch
sw.Stop();
// Record stop time and reset stopwatch
endTimes.Add(DateTime.Now.ToString("h.mm"));
sw.Reset();
// Output timespan
outputLbl.Text = sw.Elapsed.ToString();
}
Firstly, apologies for asking a question that has been asked before, but even with the examples I am not getting the desired results.
All I am trying to do is display the current time, which it does, but I noticed that the datetime format was 9:5:6 instead of 09:05:06. I read the examples about formatting DateTime but it doesn't work for some reason. Can anyone shed any light on where I am going wrong?
Thanks for your help as always.
public MainWindow()
{
InitializeComponent();
DispatcherTimer dispatchTimer = new DispatcherTimer();
dispatchTimer.Tick += new EventHandler(dispatchTimer_Tick);
dispatchTimer.Interval = new TimeSpan(0, 0, 1);
dispatchTimer.Start();
}
private void dispatchTimer_Tick(object sender, EventArgs e)
{
var hour = DateTime.Now.Hour.ToString();
var min = DateTime.Now.Minute.ToString();
var sec = DateTime.Now.Second.ToString();
var today = hour + ":" + min + ":" + sec;
label1.Content = today;
textBlock1.Text = today;
button1.Content = today;
}
Just use a custom format string:
var today = DateTime.Now.ToString("HH:mm:ss");
Or the standard one:
var today = DateTime.Now.ToString("T");
string now = DateTime.Now.ToString("HH:mm:ss");
Check TimeZoneInfo Class for more detailed globalization.
I think there are many ways to tackle this issue.
Personally, and to keep things simple, I would do it this way:
private void dispatchTimer_Tick(object sender, EventArgs e)
{
string wTime = DateTime.Now.ToString("HH:mm:ss");
// OR THIS WAY
string wTime2 = DateTime.Now.ToString("T");
label1.Content = wTime;
textBlock1.Text = wTime;
button1.Content = wTime;
}
But if you want for some reasons to keep your initial logic then this would do it too.
private void dispatchTimer_Tick(object sender, EventArgs e)
{
string hour = DateTime.Now.Hour.ToString("00");
string min = DateTime.Now.Minute.ToString("00");
string sec = DateTime.Now.Second.ToString("00");
var today = hour + ":" + min + ":" + sec;
label1.Content = today;
textBlock1.Text = today;
button1.Content = today;
}
You may also wish to look at this http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
my string is as follows:
string s ="20000101";
I would like to convert it to Date format. How can I do it?
Assuming you are using C# and .Net you will want to use DateTime.ParseExact or DateTime.TryParseExact. The format string is most likely "yyyyMMdd".
var datestring = "20000101";
var date1 = DateTime.ParseExact(datestring, "yyyyMMdd", null);
or
DateTime dateResult;
if (!DateTime.TryParseExact(datestring, "yyyyMMdd",
null, DateTimeStyles.AssumeLocal,
out dateResult))
dateResult = DateTime.MinValue; //handle failed conversion here
in C/C++, use the time.h (ctime) library's gmtime function, after converting the time to an integer: tm =gmtime(atoi(time_string));
If C#/.NET, use DateTime.Parse. If Java, use DateFormat.parse
use this to convert time
using System; using System.Collections.Generic; using
System.ComponentModel; using System.Data; using System.Drawing; using
System.Text; using System.Windows.Forms;
namespace DateTimeConvert {
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text= ConvDate_as_str(textBox1.Text);
}
public string ConvDate_as_str(string dateFormat)
{
try
{
char[] ch = dateFormat.ToCharArray();
string[] sps = dateFormat.Split(' ');
string[] spd = sps[0].Split('.');
dateFormat = spd[0] + ":" + spd[1]+" "+sps[1];
DateTime dt = new DateTime();
dt = Convert.ToDateTime(dateFormat);
return dt.Hour.ToString("00") + dt.Minute.ToString("00");
}
catch (Exception ex)
{
return "Enter Correct Format like <5.12 pm>";
}
}
private void button2_Click(object sender, EventArgs e)
{
label2.Text = ConvDate_as_date(textBox2.Text);
}
public string ConvDate_as_date(string stringFormat)
{
try
{
string hour = stringFormat.Substring(0, 2);
string min = stringFormat.Substring(2, 2);
DateTime dt = new DateTime();
dt = Convert.ToDateTime(hour+":"+min);
return String.Format("{0:t}", dt); ;
}
catch (Exception ex)
{
return "Please Enter Correct format like <0559>";
}
}
} }