How to get the day value out of a textbox in C#? - c#

For example, if the textbox contains 11/11/2016 OR 01/05/2016
How to get the day value only? example. 11 OR 01

One way is to parse the string in the TextBox to DateTime using an exact format. Then using the DateTime object, you can extract the Day Property:
DateTime date;
bool success = DateTime.TryParseExact(textBoxDate.Text, "dd/MM/yyyy",
CultureInfo.CurrentCulture,
DateTimeStyles.AssumeLocal, out date);
int day;
if(success)
{
day = date.Day; // 1
// or string stringDay = date.ToString("dd"); to get 01
}
else
{
// handle error
}
Another way that I don't prefer (Not 100% safe input validation) is to use String.Split like this:
string strDay = textBoxDate.Text.Split('/').FirstOrDefault();
int day;
if(Int32.TryParse(strDay, out day))
{
// success
}
else
{
// Handle Error
}

string myString = textbox1.text;
DateTime day = DateTime.ParseExact(myString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
int day = birthday.Day;

Related

How to convert a string to DateTime in a TextBox of a gridview [duplicate]

How do you convert a string such as 2009-05-08 14:40:52,531 into a DateTime?
Since you are handling 24-hour based time and you have a comma separating the seconds fraction, I recommend that you specify a custom format:
DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture);
You have basically two options for this. DateTime.Parse() and DateTime.ParseExact().
The first is very forgiving in terms of syntax and will parse dates in many different formats. It is good for user input which may come in different formats.
ParseExact will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. This way, you can easily detect any deviations from the expected data.
You can parse user input like this:
DateTime enteredDate = DateTime.Parse(enteredString);
If you have a specific format for the string, you should use the other method:
DateTime loadedDate = DateTime.ParseExact(loadedString, "d", null);
"d" stands for the short date pattern (see MSDN for more info) and null specifies that the current culture should be used for parsing the string.
try this
DateTime myDate = DateTime.Parse(dateString);
a better way would be this:
DateTime myDate;
if (!DateTime.TryParse(dateString, out myDate))
{
// handle parse failure
}
Use DateTime.Parse(string):
DateTime dateTime = DateTime.Parse(dateTimeStr);
Nobody seems to implemented an extension method. With the help of #CMS's answer:
Working and improved full source example is here: Gist Link
namespace ExtensionMethods {
using System;
using System.Globalization;
public static class DateTimeExtensions {
public static DateTime ToDateTime(this string s,
string format = "ddMMyyyy", string cultureString = "tr-TR") {
try {
var r = DateTime.ParseExact(
s: s,
format: format,
provider: CultureInfo.GetCultureInfo(cultureString));
return r;
} catch (FormatException) {
throw;
} catch (CultureNotFoundException) {
throw; // Given Culture is not supported culture
}
}
public static DateTime ToDateTime(this string s,
string format, CultureInfo culture) {
try {
var r = DateTime.ParseExact(s: s, format: format,
provider: culture);
return r;
} catch (FormatException) {
throw;
} catch (CultureNotFoundException) {
throw; // Given Culture is not supported culture
}
}
}
}
namespace SO {
using ExtensionMethods;
using System;
using System.Globalization;
class Program {
static void Main(string[] args) {
var mydate = "29021996";
var date = mydate.ToDateTime(format: "ddMMyyyy"); // {29.02.1996 00:00:00}
mydate = "2016 3";
date = mydate.ToDateTime("yyyy M"); // {01.03.2016 00:00:00}
mydate = "2016 12";
date = mydate.ToDateTime("yyyy d"); // {12.01.2016 00:00:00}
mydate = "2016/31/05 13:33";
date = mydate.ToDateTime("yyyy/d/M HH:mm"); // {31.05.2016 13:33:00}
mydate = "2016/31 Ocak";
date = mydate.ToDateTime("yyyy/d MMMM"); // {31.01.2016 00:00:00}
mydate = "2016/31 January";
date = mydate.ToDateTime("yyyy/d MMMM", cultureString: "en-US");
// {31.01.2016 00:00:00}
mydate = "11/شعبان/1437";
date = mydate.ToDateTime(
culture: CultureInfo.GetCultureInfo("ar-SA"),
format: "dd/MMMM/yyyy");
// Weird :) I supposed dd/yyyy/MMMM but that did not work !?$^&*
System.Diagnostics.Debug.Assert(
date.Equals(new DateTime(year: 2016, month: 5, day: 18)));
}
}
}
I tried various ways. What worked for me was this:
Convert.ToDateTime(data, CultureInfo.InvariantCulture);
data for me was times like this 9/24/2017 9:31:34 AM
Try the below, where strDate is your date in 'MM/dd/yyyy' format
var date = DateTime.Parse(strDate,new CultureInfo("en-US", true))
Convert.ToDateTime or DateTime.Parse
DateTime.Parse
Syntax:
DateTime.Parse(String value)
DateTime.Parse(String value, IFormatProvider provider)
DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)
Example:
string value = "1 January 2019";
CultureInfo provider = new CultureInfo("en-GB");
DateTime.Parse(value, provider, DateTimeStyles.NoCurrentDateDefault););
Value: string representation of date and time.
Provider: object which provides culture specific info.
Styles: formatting options that customize string parsing for some date and time parsing methods. For instance, AllowWhiteSpaces is a value which helps to ignore all spaces present in string while it parse.
It's also worth remembering DateTime is an object that is stored as number internally in the framework, Format only applies to it when you convert it back to string.
Parsing converting a string to the internal number type.
Formatting converting the internal numeric value to a readable
string.
I recently had an issue where I was trying to convert a DateTime to pass to Linq what I hadn't realised at the time was format is irrelevant when passing DateTime to a Linq Query.
DateTime SearchDate = DateTime.Parse(searchDate);
applicationsUsages = applicationsUsages.Where(x => DbFunctions.TruncateTime(x.dateApplicationSelected) == SearchDate.Date);
Full DateTime Documentation
string input;
DateTime db;
Console.WriteLine("Enter Date in this Format(YYYY-MM-DD): ");
input = Console.ReadLine();
db = Convert.ToDateTime(input);
//////// this methods convert string value to datetime
///////// in order to print date
Console.WriteLine("{0}-{1}-{2}",db.Year,db.Month,db.Day);
You could also use DateTime.TryParseExact() as below if you are unsure of the input value.
DateTime outputDateTimeValue;
if (DateTime.TryParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out outputDateTimeValue))
{
return outputDateTimeValue;
}
else
{
// Handle the fact that parse did not succeed
}
I just found an elegant way:
Convert.ChangeType("2020-12-31", typeof(DateTime));
Convert.ChangeType("2020/12/31", typeof(DateTime));
Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));
Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));
Convert.ChangeType("11/شعبان/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));
Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"
Put this code in a static class> public static class ClassName{ }
public static DateTime ToDateTime(this string datetime, char dateSpliter = '-', char timeSpliter = ':', char millisecondSpliter = ',')
{
try
{
datetime = datetime.Trim();
datetime = datetime.Replace(" ", " ");
string[] body = datetime.Split(' ');
string[] date = body[0].Split(dateSpliter);
int year = date[0].ToInt();
int month = date[1].ToInt();
int day = date[2].ToInt();
int hour = 0, minute = 0, second = 0, millisecond = 0;
if (body.Length == 2)
{
string[] tpart = body[1].Split(millisecondSpliter);
string[] time = tpart[0].Split(timeSpliter);
hour = time[0].ToInt();
minute = time[1].ToInt();
if (time.Length == 3) second = time[2].ToInt();
if (tpart.Length == 2) millisecond = tpart[1].ToInt();
}
return new DateTime(year, month, day, hour, minute, second, millisecond);
}
catch
{
return new DateTime();
}
}
In this way, you can use
string datetime = "2009-05-08 14:40:52,531";
DateTime dt0 = datetime.TToDateTime();
DateTime dt1 = "2009-05-08 14:40:52,531".ToDateTime();
DateTime dt5 = "2009-05-08".ToDateTime();
DateTime dt2 = "2009/05/08 14:40:52".ToDateTime('/');
DateTime dt3 = "2009/05/08 14.40".ToDateTime('/', '.');
DateTime dt4 = "2009-05-08 14:40-531".ToDateTime('-', ':', '-');
String now = DateTime.Now.ToString("YYYY-MM-DD HH:MI:SS");//make it datetime
DateTime.Parse(now);
this one gives you
2019-08-17 11:14:49.000
Different cultures in the world write date strings in different ways. For example, in the US 01/20/2008 is January 20th, 2008. In France this will throw an InvalidFormatException. This is because France reads date-times as Day/Month/Year, and in the US it is Month/Day/Year.
Consequently, a string like 20/01/2008 will parse to January 20th, 2008 in France, and then throw an InvalidFormatException in the US.
To determine your current culture settings, you can use System.Globalization.CultureInfo.CurrentCulture.
string dateTime = "01/08/2008 14:50:50.42";
DateTime dt = Convert.ToDateTime(dateTime);
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}, Hour: {3}, Minute: {4}, Second: {5}, Millisecond: {6}",
dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
This worked for me:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dt = DateTime.ParseExact("2009-05-08 14:40:52,531","yyyy-MM-dd HH:mm:ss,fff", provider);
Do you want it fast?
Let's say you have a date with format yyMMdd.
The fastest way to convert it that I found is:
var d = new DateTime(
(s[0] - '0') * 10 + s[1] - '0' + 2000,
(s[2] - '0') * 10 + s[3] - '0',
(s[4] - '0') * 10 + s[5] - '0')
Just, choose the indexes according to your date format of choice. If you need speed probably you don't mind the 'non-generic' way of the function.
This method takes about 10% of the time required by:
var d = DateTime.ParseExact(s, "yyMMdd", System.Globalization.CultureInfo.InvariantCulture);

How to calculate start of day and end of day from a date in c#

I have a date coming into my c# program like this: "01/15/2015", and I need to translate that to a string like this: "2015-01-15T00:00:00Z" (i.e., the beginning of that day). I am calling a 3rd party api that expects that format.
Then I need to take the same date and convert it to this: "2015-01-15T23:59:59Z" (i.e., the end of the day given).
Here is what I have, which appears to work based on the limited testing I've done, but I am wondering if this is prone to errors or if there is a better way to accomplish this. I haven't worked with dates in this format before so I thought I'd ask those with more experience. Will T23:59:59Z be the end of the day in the time zone my server is on?
program example:
class Program
{
static void Main(string[] args)
{
Search("01/15/2015");
}
private static void Search(string date)
{
//produce this:
//string startOfDay = "2015-01-15T00:00:00Z";
//string endOfDay = "2015-01-15T23:59:59Z";
DateTime temp1 = DateTime.Parse(date);
string startOfDay = temp1.ToString("yyyy-MM-ddTHH:mm:ssK") + "Z";
DateTime temp2 = DateTime.Parse(date);
string endOfDay = temp2.ToString("yyyy-MM-ddT") + "23:59:59Z";
}
}
Start of day is easy; you can just use .Date.
FYI: Please make sure you check culture.
class Program
{
static void Main(string[] args)
{
DateTime date;
if (DateTime.TryParse("01/15/2015", out date))
{
var startOfDay = date.Date;
Console.WriteLine(startOfDay.ToString("s") + "Z");
var endOfDay = date.ToEndOfDay();
Console.WriteLine(endOfDay.ToString("s") + "Z");
}
Console.ReadLine();
}
}
public static class DateExtensions
{
public static DateTime ToEndOfDay(this DateTime date)
{
return date.Date.AddDays(1).AddTicks(-1);
}
}
private static void Search(string date)
{
DateTime parsedDate;
if (DateTime.TryParseExact(date, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
{
var dateString = parsedDate.ToString("yyyy-MM-dd");
var dateStart = dateString + "T00:00:00Z";
var dateEnd = dateString + "T23:59:59Z";
}
}
This completely ignores time zones or UTC, it simply converts the incoming string to a DateTime representation and then creates the 2 strings which is that date instance formatted and appended the hard coded beginning of day and end of day as a string.
If you want to do it completely in ANSI C here ya go - And this code snip will let you goof around with it at the char level of building the time/date string from scratch. Cheers...
char time_str[22], swap_str[3]; // my time string to build and swap data
void append_tdata(int t_unit, char delimiter); // generic append with dl
main(void)
{
time_t t; // I believe everything here is ANSI C
struct tm *gmt; // and should be very portable
t = time(NULL);
gmt = gmtime(&t); // get zulu time
// start building my string with the year
itoa(gmt->tm_year + 1900, time_str, 10);
append_tdata(gmt->tm_mon, '-'); // YYYY-MM
append_tdata(gmt->tm_mday, '-'); // YYYY-MM-DD
append_tdata(gmt->tm_hour, 'T'); // YYYY-MM-DDTHH
append_tdata(gmt->tm_min, ':'); // YYYY-MM-DDTHH:MM
append_tdata(gmt->tm_sec, ':'); // YYYY-MM-DDTHH:MM:SS
time_str[strlen(time_str) + 1] = 0x0;
time_str[strlen(time_str)] = 'Z'; // YYYY-MM-DDTHH:MM:SSZ
// time_str build is done - do with it as you like
}
//---------------------------------------------------------------
void append_tdata(int t_unit, char delimiter)
{
time_str[strlen(time_str) + 1] = 0x0;
time_str[strlen(time_str)] = delimiter;
if(t_unit < 10) // is the number added to string only one digit?
{ // if so - pad it with a zero
swap_str[0] = '0';
itoa(t_unit, &swap_str[1], 10);
}
else
itoa(t_unit, swap_str, 10); // otherwise just give me the number
strcat(&time_str[strlen(time_str)], swap_str); // add it to my string plz
}

Parsing Integer Value As Datetime

I have date represented as integer like 20140820 and I want to parsing it as datetime, like 2014.08.20.
Do I need to parse each integer value (2014)(08)(02) using index or is there simpler way?
If your CurrentCulture supports yyyyMMdd format as a standard date and time format, you can just use DateTime.Parse method like;
int i = 20140820;
DateTime dt = DateTime.Parse(i.ToString());
If it doesn't support, you need to use DateTime.ParseExact or DateTime.TryParseExact methods to parse it as custom date and time format.
int i = 20140820;
DateTime dt;
if(DateTime.TryParseExact(i.ToString(), "yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
Then you can format your DateTime with .ToString() method like;
string formattedDateTime = dt.ToString("yyyy.MM.dd", CultureInfo.InvariantCulture);
The easiest and most performance way would be something like:
int date = 20140820;
int d = date % 100;
int m = (date / 100) % 100;
int y = date / 10000;
var result = new DateTime(y, m, d);
Try This :-
string time = "20140820";
DateTime theTime= DateTime.ParseExact(time,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
OR
string str = "20140820";
string[] format = {"yyyyMMdd"};
DateTime date;
DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
now date variable will have required converted date of string '20140820'
int sampleDate = 20140820;
var dateFormat = DateTime.ParseExact(sampleDate.ToString(), "yyyyMMdd",
CultureInfo.InvariantCulture).ToString("yyyy.MM.dd");
result:
2014.08.20
So, we have two competing implementations,
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
int i = 20140820;
Console.WriteLine($"StringParse:{StringParse.Parse(i)}");
Console.WriteLine($"MathParse:{MathParse.Parse(i)}");
}
}
public static class StringParse
{
public static DateTime Parse(int i)
{
return DateTime.ParseExact(
i.ToString().AsSpan(),
"yyyyMMdd".AsSpan(),
CultureInfo.InvariantCulture);
}
}
public static class MathParse
{
public static DateTime Parse(int i)
{
return new DateTime(
Math.DivRem(Math.DivRem(i, 100, out var day), 100, out var month),
month,
day);
}
}
The string approach is probably safer and probably handles edge cases better.
Both will be fast and unlikely to be a performance bottle neck but it is my untested assertion that the math approach probably has better performance.

split comma separated string in c# and needs to save it in two separate variables

I have to split the comma - separated string in c# and needs to save it in two variables. The C# function is as follows :
public int InsertLogDetails(string RunIDStartTime, int Distribution_ID, List<string> additions, List<string> removals, bool status, string ErrorMessage)
{
int Run_ID=0;
DateTime StartTime=DateTime.Now;
//Needs to split RunIDStartTime and needs to save it in Run_ID and StartTime
}
The RunIDStartTime holds the value of Run_ID ans StartTime.(Eg: 5,Jan 23 2013 9:31AM)
Anybody please helpout. Thanks in advance.
Here is a working answer and you do not need to do .ToArray because Split already returns an array.
var RunIDStartTime = "5,Jan 23 2013 9:31AM";
var listSplit = RunIDStartTime.Split(',');
var id = int.Parse(listSplit[0]);
var dateTime = DateTime.Parse(listSplit[1]);
returns id = 5 and date = Jan 23 2013 9:31AM
Use int.TryParse and DateTime.TryParseExact with DateFormat to parse the string. To Split, using string.Split, Something like:
string RunIDStartTime = "5,Jan 23 2013 9:31AM";
int Run_ID = 0;
DateTime StartTime = DateTime.MinValue;
string[] splittedArray = RunIDStartTime.Split(',');
if (splittedArray.Length >= 2)
{
if (int.TryParse(splittedArray[0], out Run_ID))
{
//valid ID
}
else
{
//Invalid ID
}
if(DateTime.TryParseExact(splittedArray[1],"MMM d yyyy h:mmtt",CultureInfo.InvariantCulture,DateTimeStyles.None, out StartTime))
{
//Valid date
}
else
{
//invalid date
}
}
For output:
Console.WriteLine("ID : {0} Date: {1}", Run_ID, StartTime.ToString());
Output:
ID : 5 Date: 23/01/2013 9:31:00 AM
public int InsertLogDetails(string RunIDStartTime, int Distribution_ID, List<string> additions, List<string> removals, bool status, string ErrorMessage)
{
var tokens = RunIDStartTime.split(',');
int Run_ID= int.Parse(tokens[0]);
DateTime StartTime = DateTime.Parse(tokens[1],"MMM d yyyy h:mmtt", CultureInfo.InvariantCulture, DateTimeStyles.None);
}

Watin:Get date from textfield

I have a textfield that has a date with the format "12/23/2010".Is there away for me to get the number 23 using watin ie get number from textfield;i'm gonna use it like this.
1.Get datetime 12/23/2010 and get number '23'
2.substract 2 from 23 and store it somewhere[ie: 23 - 2 = 21]
3.Insert the new datetime number [ie:12/21/2010 ]
string myDate = browser.TextField(Find.ByName("myTextField")).Value;
DateTime time = = new DateTime();
time2 = time - 2;
browser.TextField(Find.ByName("myTextField")).TypeText(time2);
Is this possible?or should i be looking to another way.Ask the user to insert the data instead.
Try this :
string myDate = browser.TextField(Find.ByName("myTextField")).Value;
DateTime time = = new DateTime();
if(DateTime.TryParse(myDate, out time);) {
Console.WriteLine(time.Month);
}
else {
//Not a valid date.
}

Categories