How to get string value from another string? - c#

I have a textBox1 showing text = 01/02/2013, and I have
string year, month, day.
How to set
year=2013,
month=02,
day=01
from textbox1

var text = "01/02/2013";
var parts = text.Split('/');
var day = parts[0];
var month = parts[1];
var year = parts[2];

Just to be different and to add a solution that is not splitting the string, here is one converting the string to a DateTime and pulling the information out of the resulting DateTime Object.
class Program
{
static void Main(string[] args)
{
string myString = "01/02/2013";
DateTime tempDate;
if (!DateTime.TryParse(myString, out tempDate))
Console.WriteLine("Invalid Date");
else
{
var month = tempDate.Month.ToString();
var year = tempDate.Year.ToString();
var day = tempDate.Day.ToString();
Console.WriteLine("The day is {0}, the month is {1}, the year is {2}", day, month, year);
}
Console.ReadLine();
}
}

Use string.Split to get each string
string s = "01/02/2013";
string[] words = s.Split('/');
foreach (string word in words)
{
Console.WriteLine(word);
}

Try this Regex
(?<month>\d{1,2})\/(?<day>\d{1,2})\/(?<year>\d{4})
I/P:
2/7/2014
O/P:
month 2
day 7
year 2014
REGEX DEMO
(Or)
Try by String.Split method
string[] separators = {"-","/",":"};
string value = "01/02/2013";
string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (void word_loopVariable in words)
{
word = word_loopVariable;
Console.WriteLine(word);
}

Related

Remove string part in a variable containing date in c#

I have a string variable that holds the value of "02/04/2018 to 08/04/2018".
string dateRange = "02/04/2018 to 08/04/2018";
I have a function in c# that gets all the date within the range of 02/04/2018 to 08/04/2018 as per below.
public string getDateRange(string dateRange) {
var selectedDates = new List<DateTime?>();
for (var date = Convert.ToDateTime("02/04/2018");
date <= Convert.ToDateTime("08/04/2018");
date = date.AddDays(1)) {
selectedDates.Add(date);
}
foreach (var date in selectedDates) {
Console.WriteLine(date);
}
return selectedDates;
}
What I want to achieve in this method is to remove the word to in the date range and pass the starting date and ending date separately. Can someone please help ?
You can use String.Split() to separate the dates:
public string[] separateDates(string dateRange)
{
string[] dateSplit = dateRange.Split(new string[] { "to" }, StringSplitOptions.RemoveEmptyEntries);
return new string[]{dateSplit[0].Trim(), dateSplit[1].Trim()};
}
The method returns a string array that holds the first ("02/04/2018") and the second date ("08/04/2018"):
static void Main()
{
string dateRange = "02/04/2018 to 08/04/2018";
string[] myDates = separateDates(dateRange);
string firstDate = myDates[0];//"02/04/2018"
string secondDate = myDates[1];//"08/04/2018"
}
EDIT:
I have implemented my method that separates the dates into your method:
public List<DateTime?> getDateRange(string dateRange)
{
var selectedDates = new List<DateTime?>();
string[] dateSplit = dateRange.Split(new string[] { "to" }, StringSplitOptions.RemoveEmptyEntries);
for (var date = Convert.ToDateTime(dateSplit[0].Trim());
date <= Convert.ToDateTime(dateSplit[1].Trim());
date = date.AddDays(1))
{
selectedDates.Add(date);
}
foreach (var date in selectedDates)
{
Console.WriteLine(date.Value.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
}
return selectedDates;
}
The method now returns List<DateTime?> instead of string because the type of selectedDates is List<DateTime?>. I also made a modification to the console output, now the dates are printing to the console in the following format dd/MM/yyyy (e.g. 02/04/2018).
LastIndexOf: This method searches strings from the right. It finds the location of the last occurrence of a letter or substring. It is the reversed version of IndexOf.
public static void Main(string[] args)
{
string str = "02/04/2018 to 08/04/2018";
int pos = str.LastIndexOf("to");
string result = str.Substring(0, pos) + " " + str.Substring(pos + 2);
Console.WriteLine(result);
}
Fiddle
Its printing the date as : 02.04.2018 00:00:00. I have specified the string to dd/MM/yyyy. It just removes the 00:00:00 but keeps the dot in between.
Here is the little amendment to fix that:
Console.WriteLine(date.Value.ToString("dd/MM/yyyy"));

How can i get the arrray months to be displayed in the console?

static void Main(string[] args)
{
string[] months = File.ReadAllLines("Month.txt");
Console.WriteLine(months);
}
Just iterate through each item in the collection using a foreach loop :
string[] months = File.ReadAllLines("Month.txt");
foreach(var month in months)
{
Console.WriteLine(month);
}
Other approaches might include a plain for loop :
for(var m = 0; m < months.Length; m++)
{
Console.WriteLine(months[m]);
}
Or if you needed them as a comma-delimited string, you could use the String.Join() method :
// Yields "January,February,March..."
Console.WriteLine(String.Join(',', months));
Or without Foreach by using String.Join:
string[] months = File.ReadAllLines("Month.txt");
string str = String.Join("\n",months);
//Or string str = String.Join(Environment.NewLine, months);
Console.WriteLine(str);
Console.ReadLine();
string[] months = File.ReadAllLines("Month.txt");
string str =string.Empty;
foreach (var item in months)
{
str = item + ";";
}
Console.WriteLine(str);

How to remove first two characters from a date string (MM/dd/yyyy) in array?

I have an array that stores date input from users but I want to remove or trim the first two characters (basically, I want to remove the month) from every date inputted in the array:
class MainClass
{
{
//Main Program....
}
public static int GetInput (string[] date)
{
int loop;
(for int i=0 ; i < loop ; i++)
dArray[i] = Console.ReadLine();
}
}
class OtherClass
{
//Required data properties, etc...
public string TrimFirstTwoMonthChar(string dateInput)
{
char[] delimiter = {'/', '-', .... }
string[] monthNumberRemoved = dateInput.Split(delimeter);
// How would I code the rest of this function so that it removes the first 2 characters from "MM/dd/yyyy".
//Keep in mind I have also allowed users to input the date in formats like
//"M/dd/yyyy" (such as 3/07/2011 vs 03/07/2011)
//so sometimes I would only need to remove ONE NOT TWO of the month character //
}
}
With string, you can use a simple substring:
public static string TrimFirstTwoMonthChar(string dateInput)
{
var indexOfFirstBar = dateInput.IndexOf('/');
var start = indexOfFirstBar + 1;
return dateInput.Substring(start, dateInput.Length - start);
}
But I suggest you to convert to DateTime and use the date format you want:
public static string TrimFirstTwoMonthChar(string dateInput)
{
var date = Convert.ToDateTime(dateInput);
return date.ToString("dd/yyyy"); // Use the format you want here
}
About Convert.ToDateTime and date formats.
Something like this?
public string TrimFirstTwoMonthChar(string dateInput)
{
char[] delimiter = {'/', '-', .... }
string[] monthNumberRemoved = dateInput.Split(delimeter);
return monthNumberRemoved[1] + "/" + monthNumberRemoved[2];
}

Parsing a string with, seemingly, no delimiter

I have the following string that I need to parse out so I can insert them into a DB. The delimiter is "`":
`020 Some Description `060 A Different Description `100 And Yet Another `
I split the string into an array using this
var responseArray = response.Split('`');
So then each item in the responseArrray[] looks like this: 020 Some Description
How would I get the two different parts out of that array? The 1st part will be either 3 or 4 characters long. 2nd part will be no more then 35 characters long.
Due to some ridiculous strangeness beyond my control there is random amounts of space between the 1st and 2nd part.
Or put the other two answers together, and get something that's more complete:
string[] response = input.Split(`);
foreach (String str in response) {
int splitIndex = str.IndexOf(' ');
string num = str.Substring(0, splitIndex);
string desc = str.Substring(splitIndex);
desc.Trim();
}
so, basically you use the first space as a delimiter to create 2 strings. Then you trim the second one, since trim only applies to leading and trailing spaces, not everything in between.
Edit: this a straight implementation of Brad M's comment.
You can try this solution:
var inputString = "`020 Some Description `060 A Different Description `100 And Yet Another `";
int firstWordLength = 3;
int secondWordMaxLength = 35;
var result =inputString.Split('`')
.SelectMany(x => new[]
{
new String(x.Take(firstWordLength).ToArray()).Trim(),
new String(x.Skip(firstWordLength).Take(secondWordMaxLength).ToArray()).Trim()
});
Here is the result in LINQPad:
Update: My first solution has some problems because the use of Trim after Take.Here is another approach with an extension method:
public static class Extensions
{
public static IEnumerable<string> GetWords(this string source,int firstWordLengt,int secondWordLenght)
{
List<string> words = new List<string>();
foreach (var word in source.Split(new[] {'`'}, StringSplitOptions.RemoveEmptyEntries))
{
var parts = word.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
words.Add(new string(parts[0].Take(firstWordLengt).ToArray()));
words.Add(new string(string.Join(" ",parts.Skip(1)).Take(secondWordLenght).ToArray()));
}
return words;
}
}
And here is the test result:
Try this
string response = "020 Some Description060 A Different Description 100 And Yet Another";
var responseArray = response.Split('`');
string[] splitArray = {};
string result = "";
foreach (string it in responseArray)
{
splitArray = it.Split(' ');
foreach (string ot in splitArray)
{
if (!string.IsNullOrWhiteSpace(ot))
result += "-" + ot.Trim();
}
}
splitArray = result.Substring(1).Split('-');
string[] entries = input.Split('`');
foreach (string s in entries)
GetStringParts(s);
IEnumerable<String> GetStringParts(String input)
{
foreach (string s in input.Split(' ')
yield return s.Trim();
}
Trim only removes leading/trailing whitespace per MSDN, so spaces in the description won't hurt you.
If the first part is an integer
And you need to account for some empty
For me the first pass was empty
public void parse()
{
string s = #"`020 Some Description `060 A Different Description `100 And Yet Another `";
Int32 first;
String second;
if (s.Contains('`'))
{
foreach (string firstSecond in s.Split('`'))
{
System.Diagnostics.Debug.WriteLine(firstSecond);
if (!string.IsNullOrEmpty(firstSecond))
{
firstSecond.TrimStart();
Int32 firstSpace = firstSecond.IndexOf(' ');
if (firstSpace > 0)
{
System.Diagnostics.Debug.WriteLine("'" + firstSecond.Substring(0, firstSpace) + "'");
if (Int32.TryParse(firstSecond.Substring(0, firstSpace), out first))
{
System.Diagnostics.Debug.WriteLine("'" + firstSecond.Substring(firstSpace-1) + "'");
second = firstSecond.Substring(firstSpace).Trim();
}
}
}
}
}
}
You can get the first part by finding the first space and make a substring. The second is also a Substring. Try something like this.
foreach(string st in response)
{
int index = response.IndexOf(' ');
string firstPart = response.Substring(0, index);
//string secondPart = response.Substring(response.Lenght-35);
//better use this
string secondPart = response.Substring(index);
secondPart.Trim();
}

How to get the day name from a selected date?

I have this : Datetime.Now(); or 23/10/2009
I want this : Friday
For local date-time (GMT-5) and using Gregorian calendar.
//default locale
System.DateTime.Now.DayOfWeek.ToString();
//localized version
System.DateTime.Now.ToString("dddd");
To make the answer more complete:
DayOfWeek MSDN article
If localization is important, you should use the "dddd" string format as Fredrik pointed out - MSDN "dddd" format article
If you want to know the day of the week for your code to do something with it, DateTime.Now.DayOfWeek will do the job.
If you want to display the day of week to the user, DateTime.Now.ToString("dddd") will give you the localized day name, according to the current culture (MSDN info on the "dddd" format string).
System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(System.DateTime.Now.DayOfWeek)
or
System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(DateTime.Parse("23/10/2009").DayOfWeek)
DateTime.Now.DayOfWeek quite easy to guess actually.
for any given date:
DateTime dt = //....
DayOfWeek dow = dt.DayOfWeek; //enum
string str = dow.ToString(); //string
Here is more simple
DateTime dt;
string yourdate = dt.DayOfWeek.ToString()
better than declare redundant DayOfWeek
DateTime now = DateTime.Now
string s = now.DayOfWeek.ToString();
try this:
DateTime.Now.DayOfWeek
You're looking for the DayOfWeek property.
Here's the msdn article.
What about if we use String.Format here
DateTime today = DateTime.Today;
String.Format("{0:dd-MM}, {1:dddd}", today, today) //In dd-MM format
String.Format("{0:MM-dd}, {1:dddd}", today, today) //In MM-dd format
(DateTime.Parse((Eval("date").ToString()))).DayOfWeek.ToString()
at the place of Eval("date"),you can use any date...get name of day
I use this Extension Method:
public static string GetDayName(this DateTime date)
{
string _ret = string.Empty; //Only for .NET Framework 4++
var culture = new System.Globalization.CultureInfo("es-419"); //<- 'es-419' = Spanish (Latin America), 'en-US' = English (United States)
_ret = culture.DateTimeFormat.GetDayName(date.DayOfWeek); //<- Get the Name
_ret = culture.TextInfo.ToTitleCase(_ret.ToLower()); //<- Convert to Capital title
return _ret;
}
Random Rnd = new Random();
RandomDates Rdate = new RandomDates();
PaymentDetails Payd = new PaymentDetails();
DayOfWeek strDay = DateTime.Today.DayOfWeek;
var dateTime = DateTime.Now;
var dateValue2 = dateTime.ToString(#"MM\/dd\/yyyy");
StepDescription = "Fill MatterInformation. ";
Console.Write(" Input the Day : ");
dt = Convert.ToInt32(Console.ReadLine());
Console.Write(" Input the Month : ");
mn = Convert.ToInt32(Console.ReadLine());
Console.Write(" Input the Year : ");
yr = Convert.ToInt32(Console.ReadLine());
DateTime d = new DateTime(2021, 04, yr);
var culture = System.Threading.Thread.CurrentThread.CurrentCulture;
var diff = d.DayOfWeek - culture.DateTimeFormat.FirstDayOfWeek;
if (diff < 0)
diff += 7;
var x = d.AddDays(-diff).Date;
dateTime = DateTime.Now;
dateValue2 = dateTime.ToString(#"MM\/dd\/yyyy");
Console.WriteLine($"Date Value: {dateValue2}");
// strDay =
}
if (!strDay.Equals("Sunday") | !strDay.Equals("Saturday"))
{
Console.WriteLine("___________________OK____________________________________________");
// string NotificateionDate = Rdate.DateWithin_PastDays(Rnd.Next(30, 260)).ToString(#"MM\/dd\/yyyy");
// CustomLibrary.seWaitUntilElementIsVisible(10, NotiFiedDateTab.Actions.seGetLocator(), "NotiFiedDateTab");
NotiFiedDateTab.Actions.Set(ControlPropertyNames.Text, dateValue2);
}
else
{
Console.WriteLine("_________________________NOT______________________________________");
if (strDay.Equals("Sunday"))
{
dateTime = dateTime.AddDays(-2);
dateValue2 = dateTime.ToString(#"MM\/dd\/yyyy");
NotiFiedDateTab.Actions.Set(ControlPropertyNames.Text, dateValue2);
}
else if (strDay.Equals("Saturday"))
{
dateTime = dateTime.AddDays(-1);
dateValue2 = dateTime.ToString(#"MM\/dd\/yyyy");
NotiFiedDateTab.Actions.Set(ControlPropertyNames.Text, dateValue2);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessTheDay
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the Day Number ");
int day = int.Parse(Console.ReadLine());
Console.WriteLine(" Enter The Month");
int month = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Year ");
int year = int.Parse(Console.ReadLine());
DateTime mydate = new DateTime(year,month,day);
string formatteddate = string.Format("{0:dddd}", mydate);
Console.WriteLine("The day should be " + formatteddate);
}
}
}

Categories

Resources