Convert string to Date format - c#

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>";
}
}
} }

Related

Validate Date entered into a DataGridView

I am trying to validate an entered Date value in a DataGridViewCell by users and if the value does not match the a specific scheme, it should give the user a message like
entered value should match dd/MM/yyyy format
I tried below code on CellValidating event
private void DGV_PatientSessions_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (DGV_PatientSessions.Columns[e.ColumnIndex].Name == "DGV_PatientSessions_Date")
{
string DateValue;
DateTime DateFormated;
DateValue = DGV_PatientSessions.CurrentRow.Cells["DGV_PatientSessions_Date"].Value.ToString();
if (DateTime.TryParseExact(DateValue, "dd/MM/yyyy", new CultureInfo("ar-SY"), DateTimeStyles.None, out DateFormated))
{
MessageBox.Show("done");
}
}
}
but I still get message error below
I tried to use regex which not recommended as I found when I searched but it wont work
string DateFormat;
DateFormat = DGV_PatientSessions.CurrentRow.Cells["DGV_PatientSessions_Date"].Value.ToString();
if(Regex.IsMatch(DateFormat, #"(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$"))
{
MessageBox.Show("done");
}
else
{
MessageBox.Show("value should match dd/MM/yyyy format);
}
You need to cancel the edit if the data entered is not valid using e.Cancel = true;:
private void DGV_PatientSessions_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (DGV_PatientSessions.Columns[e.ColumnIndex].Name == "DGV_PatientSessions_Date")
{
string DateValue;
DateTime DateFormated;
DateValue = DGV_PatientSessions.CurrentRow.Cells["DGV_PatientSessions_Date"].Value.ToString();
if (DateTime.TryParseExact(DateValue, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateFormated))
{
MessageBox.Show("done");
}
else
{
MessageBox.Show("value should match dd/MM/yyyy format");
e.Cancel = true; // The important part
}
}
}

Disable all dates after some months from a certain date Android DatePicker

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();
}

If statement for fileOut not working properly

I am fairly new to C# programming and am having some trouble figuring out how to perform this. I am trying to say in the program that if the textBoxes are not filled in than streamWriter should not send anything to the file and a messageBox pops up. As of now only the messageBox pops up but information is still being sent to the file. I am trying to use something like this if ((fileOut != null)) however I am not finding a good place to insert it or if this is what should be used. Any help would be much appreciated. Thanks!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Calculate payroll
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
decimal hoursWorked;
decimal hourlyPayRate;
decimal basePay;
decimal overtimeHours;
decimal overtimePay;
decimal grossPay;
// Get the hours worked and hourly pay rate.
hoursWorked = decimal.Parse(txtHoursWorked.Text);
hourlyPayRate = decimal.Parse(txtHourlyRate.Text);
// Determine the gross pay.
if (hoursWorked >= 40)
{
// Calculate the base pay (without overtime).
basePay = hourlyPayRate * 40;
// Calculate the number of overtime hours.
overtimeHours = hoursWorked - 40;
// Calculate the overtime pay.
overtimePay = overtimeHours * hourlyPayRate * 1.5m;
// Calculate the gross pay.
grossPay = basePay + overtimePay;
}
else
{
// Calculate the gross pay.
grossPay = hoursWorked * hourlyPayRate;
}
// Display the gross pay.
lblGrossPay.Text = Convert.ToString(grossPay);
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
} //Writes text to files
StreamWriter fileOut = new StreamWriter("employeePay.dat", true);
//if (!(fileOut != null))//I am trying this. However stated this way nothing is passed to the file
{
fileOut.Write(txtName.Text);
fileOut.Write(",");
fileOut.Write(txtNumber.Text);
fileOut.Write(",");
fileOut.Write(txtHourlyRate.Text);
fileOut.Write(",");
fileOut.Write(txtHoursWorked.Text);
fileOut.Write(",");
fileOut.WriteLine(lblGrossPay.Text);
}
fileOut.Close();
LoadContacts();
}
// Clear all text from output labels & input textboxes
private void btnClera_Click(object sender, EventArgs e)
{
// Clear the TextBoxes and gross pay label.
txtName.Text = "";
txtNumber.Text = "";
txtHoursWorked.Text = "";
txtHourlyRate.Text = "";
lblGrossPay.Text = "";
// Reset the focus.
//txtHoursWorked.Focus();
}
// End program
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
void LoadContacts()
{
try
{
lstEmployeePay.Items.Clear();
string employeePay;
if (File.Exists("employeePay.dat"))
{
StreamReader fileIn = new StreamReader("employeePay.dat");
while (!fileIn.EndOfStream)
{
employeePay = fileIn.ReadLine();
string[] fields = employeePay.Split(',');
lstEmployeePay.Items.Add(fields[0]);
lstEmployeePay.Items.Add(fields[1]);
lstEmployeePay.Items.Add(fields[2]);
lstEmployeePay.Items.Add(fields[3]);
lstEmployeePay.Items.Add(fields[4]);
lstEmployeePay.Items.Add("");
}
fileIn.Close();
}
}
catch (FileNotFoundException ex)
{
MessageBox.Show("The file does not exist, please try again");
}
catch (Exception ex)
{
}
}
}
}
All you need is a return statement after showing the message box. Like
MessageBox.Show("");
return;
I would also like to make some other recommendations here.
You can check if the textboxes are empty by doing
if(string.IsNullorWhiteSpace(yourtextboxt.text)
You should do the parsing using decimal.tryparse. It will not throw an exception.
You need to move your stream writer within the exception handling as everything after the catch still gets executed.
I would also consider wrapping the StreamWriter in a using statement to guarantee it is closed when the function exits.
try
{
// other code here
using(var fileOut = new StreamWriter("employeePay.dat", true)
{
fileOut.Write(txtName.Text);
fileOut.Write(",");
fileOut.Write(txtNumber.Text);
fileOut.Write(",");
fileOut.Write(txtHourlyRate.Text);
fileOut.Write(",");
fileOut.Write(txtHoursWorked.Text);
fileOut.Write(",");
fileOut.WriteLine(lblGrossPay.Text);
}
}
catch(...)
{
MessageBox();
}
// any code after the catch will still execute

Databound DateTimePicker Time in C#

I'm have a Windows Form with 2 datetimepicker controls: one for date and a separate datetimepicker control for time. Both of these controls are bound to the same column in a database and the controls have different property names (i.e., dateEdit and timeEdit) and different formats (i.e., Long and Time).
Here are my problems/questions:
The timeEdit picker ignores whatever seconds are in the database entry and sets the time seconds to "00", as in "2:34:00", even though the database entry (trimmed to time for this illustration) is "14:34:31.891123 -04:00". How can I get the seconds to correctly display?
Whenever I edit the seconds in the timeEdit picker from "00" to (for example) "15", as in "2:34:15", the picker resets the seconds to "00" before passing the value to the next function. How do I pass the correct seconds value?
I'd like to edit the milliseconds on the time. Is it best for me to bind the trimmed milliseconds (using DATEPART) to a text box? Will I need to convert or cast the milliseconds to a char or string in order to correctly display them in a text box?
Thanks for any help!
Code to trigger the edit form:
private void timeDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex == 5)
{
EditTime editForm = new EditTime((Guid)timeDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
editForm.StartPosition = FormStartPosition.CenterScreen;
editForm.ShowDialog();
editForm.Close();
}
}
catch (Exception ex)
{
string msg = "Error: ";
msg += ex.Message;
throw new Exception(msg);
}
}
Code for the form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace StatusManager
{
public partial class EditTime : Form
{
private Guid calendarId;
public EditTime()
{
InitializeComponent();
}
public EditTime(Guid Id)
{
InitializeComponent();
calendarId = Id;
}
public string GetConnectionString()
{
var connString = ConfigurationManager.ConnectionStrings["StatusManager.Properties.Settings.StatusConnectionString"].ConnectionString;
return connString;
}
private void UpdateCalendarItem(string dateEdit, string timeEdit, string note)
{
var conn = new SqlConnection(GetConnectionString());
const string UpdateStatusSql = #"UPDATE dbo.statuses SET
calendarTime = #timeOffset
notes = #note
WHERE PK_calendarUID = #PK_calendarUID";
try
{
SqlCommand cmd = new SqlCommand(UpdateSql, conn);
var param = new SqlParameter[3];
param[0] = new SqlParameter("#PK_calendarUID", calendarId);
//Convert date(s) to correct format
string dateTimeCombined = dateEdit + " " timeEdit;
DateTime timeConverted = Convert.ToDateTime(dateTimeCombined);
DateTimeOffset timeOffset = new DateTimeOffset(timeConverted);
param[1] = new SqlParameter("#timeOffset", timeOffset);
param[2] = new SqlParameter("#note", note);
foreach (SqlParameter t in param)
{
cmd.Parameters.Add(t);
}
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string msg = "Error updating 'calendarItems': ";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
private void editTimeButton_Click(object sender, EventArgs e)
{
UpdateCalendarItem(dateEdit.Text, timeEdit.Text, notes.Text);
this.Close();
}
private void EditTime_Load(object sender, EventArgs e)
{
this.locationsTableAdapter.Fill(this.locationsDataSet.locations);
this.calendarTableAdapter.FillById(this.calendarDataSet.calendarItems, calendarId);
}
}
}
Code for instantiating the datetimepicker:
this.timeEdit.CustomFormat = "";
this.timeEdit.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.calendarBindingSource, "calendarTime", true));
this.timeEdit.Format = System.Windows.Forms.DateTimePickerFormat.Time;
this.timeEdit.Location = new System.Drawing.Point(385, 30);
this.timeEdit.Name = "timeEdit";
this.timeEdit.ShowUpDown = true;
this.timeEdit.Size = new System.Drawing.Size(89, 20);
this.timeEdit.TabIndex = 2;
You need to use DateTimePicker.CustomFormat Property
s The one- or two-digit seconds.
ss The two-digit seconds. Single digit values are preceded by a 0.
You can't use DateTimePicker for milliseconds.
Problem solved but I'm not exactly sure how. Here's what I did:
In calendarDataSet, I updated both queries (Fill,GetData and FillById,GetDataBy (#ID)) to select calendarTime as CONVERT(VARCHAR(12), calendarTime, 114) AS calHoursMinsSec
In essence, I created created a new column with the hours, minutes, seconds, and milliseconds
On the form, I added a textbox and bound the textbox to calHoursMinsSec
Note: My previous attempts to convert the datetime to a varchar to were unsuccessful no doubt due to operator error.
Once I saved the form, the binding seemed to stick and I was able to pass the relevant variables to the update function
Thanks for everyone's input! I appreciate the guidance and suggestions!

Regular Expressions in C# kill program

I'm doing a program for a class, and when I run it and type something in the txtSSN control that's not valid, it freezes up and crashes. I can't figure it out because I have another very similar project that works just fine.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace VitalStatistics
{
public partial class frmVitalStatistics : Form
{
#region Declarations
const String AppTitle = "Vital Statistics";
const float hoursOffset = 24.999F;
Regex ssnRegex;
#endregion
#region Constructors
public frmVitalStatistics()
{
InitializeComponent();
}
#endregion
#region Event Handlers
private void frmVitalStatistics_Load(object sender, EventArgs e)
{
// Initialize SSN input control
RegexOptions options = RegexOptions.IgnorePatternWhitespace;
string pattern = #"\A\d{3}-\d{3}-\d{4}\Z";
ssnRegex = new Regex(pattern, options);
// Init. Gender controls
optGender = Gender.Unassigned;
rbFemale.Tag = Gender.Male;
rbMale.Tag = Gender.Female;
// Init dtpBirth controls
dtpBirth.MinDate = DateTime.Today;
dtpBirth.MaxDate = DateTime.Today.AddHours(hoursOffset);
dtpBirth.Value = DateTime.Today;
}
private void btnSubmit_Click(object sender, EventArgs e)
{
string name = String.Empty;
string ssn = String.Empty;
int length = 0;
int weight = 0;
DateTime birthDate = DateTime.MinValue;
Gender gender = Gender.Unassigned;
//Gather inputs
if (GetName(ref name) &&
GetSSN(ref ssn) &&
GetLength(ref length) &&
GetWeight(ref weight) &&
GetGender(ref gender) &&
GetBirthDate(ref birthDate))
{
//submit & close
string format =
"Thank you for submitting your contact information. \n\n" +
"Name: {0}\n" +
"SSN: {1}\n" +
"Length: {2}\n" +
"Weight: {3}\n" +
"Gender: {4}\n" +
"Birth Date & Time: {5:D}\n";
string msg = String.Format(format, name, ssn, length, weight, gender, birthDate);
MessageBox.Show(msg,AppTitle);
Close();
}
}
private Gender optGender;
private void Gender_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = (RadioButton)sender;
optGender = (rb.Checked ? (Gender)rb.Tag : Gender.Unassigned);
}
#endregion
#region Implementation
bool GetName(ref string name)
{
if (String.IsNullOrWhiteSpace(txtName.Text))
{
txtName.SelectAll();
txtName.Focus();
ShowError("Please enter your name.\n Names cannot consist of whitespace.");
return false;
}
name = txtName.Text.Trim();
return true;
}
bool GetSSN(ref string ssn)
{
txtSSN.Text = txtSSN.Text.Trim();
Match match = ssnRegex.Match(txtSSN.Text);
if (!match.Success)
{
txtSSN.SelectAll();
txtSSN.Focus();
ShowError("Unrecognized format for SSN. Please enter in the following format: 000-000-0000.");
return false;
}
ssn = txtSSN.Text;
return true;
}
bool GetLength(ref int length)
{
int value;
try
{
if (String.IsNullOrWhiteSpace(txtLength.Text))
throw new ArgumentException("Field cannot be empty or contain spaces.");
value = int.Parse(txtLength.Text);
}
catch (Exception ex)
{
// Select text and set focus
txtLength.SelectAll();
txtLength.Focus();
// Set up error Message
string msg = String.Format("{0}", ex);
ShowError(ex.Message);
return false;
}
length = value;
return true;
}
bool GetWeight(ref int weight)
{
int value;
try
{
if (String.IsNullOrWhiteSpace(txtWeight.Text))
throw new ArgumentException("Field cannot be empty or contain spaces.");
value = int.Parse(txtLength.Text);
}
catch (Exception ex)
{
// Select text and set focus
txtWeight.SelectAll();
txtWeight.Focus();
// Set up error Message
string msg = String.Format("{0}", ex);
ShowError(ex.Message);
return false;
}
weight = value;
return true;
}
bool GetGender(ref Gender gender)
{
if (optGender == Gender.Unassigned)
{
ShowError("Select a Gender.");
return false;
}
gender = optGender;
return true;
}
bool GetBirthDate(ref DateTime birthDate)
{
birthDate = dtpBirth.Value;
return true;
}
void ShowError(string msg)
{
MessageBox.Show(msg, AppTitle, MessageBoxButtons.OK, MessageBoxIcon.None);
}
#endregion
}
}
Judging by the comments and the code it sounds as if you don't have the event handler frmVitalStatistics_Load connected to the load event of the form. This would cause a null pointer exception which would be consistent the error you are seeing.
As per my comments to the OP, if frmVitalStatistics_Load isn't running, it may not be hooked up right as an event handler.
I have been unable to reproduce the error you are seeing with the code you posted. There is likely something in your frmVitalStatistics.Designer.cs file that is different than what I came up with.
As others have said, it could be an event that is missing or perhaps an extra event hooked up that isn't needed.
These are the only events I have hooked up in the form.
this.rbMale.CheckedChanged += new System.EventHandler(this.Gender_CheckedChanged);
this.rbFemale.CheckedChanged += new System.EventHandler(this.Gender_CheckedChanged);
this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
this.Load += new System.EventHandler(this.frmVitalStatistics_Load);
Check your frmVitalStatistics.Designer.cs and see if you have any others or if any of these are missing.
One question... Is it freezing AS you are typing or after you click Submit?

Categories