Can anybody tell me the best approach or solution on how I would do the following?
I have a DateTime (as String) in following format:
string test = "21.12.2013";
How could I now remove all zero's from the month and day but still 'keep' the DateTime Logic:
//Example 1
string input = "06.10.2013" // 6th October
string output = "6.10.2013" //only remove '0' from the day
//Example 2
string input = "01.09.2012" // 1st September
string output = "1.9.2012" //remove from month and day
//Example 3
string input = "20.10.2011" // 20th October
string output = "20.10.2011" //should (must) stay!
I can also parse to DateTime if that would be make it easier but yeah I hope you got my idea...
Any help appreciated!
Parsing your string into DateTime and getting it back to string using ToString with desired patter seems to be the easiest way to go:
public static string GetRidOfZeros(string input)
{
var dt = DateTime.ParseExact(input, "dd.MM.yyyy", CultureInfo.InvariantCulture);
return dt.ToString("d.M.yyyy", CultureInfo.InvariantCulture);
}
Little testing, with your sample data:
var inputs = new List<string> { "06.10.2013", "01.09.2012", "20.10.2011" };
var outputs = new List<string> { "6.10.2013", "1.9.2012","20.10.2011" };
if(outputs.SequenceEqual(inputs.Select(d => GetRidOfZeros(d))))
Console.WriteLine("Output is OK");
else
Console.WriteLine("Collections does not match.");
Prints Output is OK.
DateTime.Parse(input).ToString("d.M.yyyy")
As you said, parsing to DateTime first would probably make things easier, since then you can just use:
myDateTime.ToString("d.M.yyyy");
When you parse it you can use ToString to format it any way you like:
var date = "06.10.2013";
DateTime parsed = DateTime.ParseExact(date, "dd.MM.yyyy", CultureInfo.InvariantCulture);
var noZerosHere = parsed.ToString("d.MM.yyyy");
A decent "catch-all" method (that will work not just on DateTime but ANY kind of string) would be to split the string up, take out leading zeroes and then put the pieces back together again.
string input = "01.09.2012";
string[] values = input.Split(".");
string[] modifiedValues = values.Select(x => x.TrimStart('0');
string output = String.Join(".", modifiedValues);
You can adjust the delimiters for different representations of DateTime, e.g. those that use slashes (01/09/2012) or are written in a different order.
Related
I want to swap two values in a STRING
This is an example of doing it with characters:
string str = "PQRQP";
var res= str.Select(a=> a == 'P' ? 'Q' : (a=='Q' ? 'P' : a)).ToArray();
str = new String(res);
Console.WriteLine(str);
But my string is 2/7/2019, where i want to swap the 2 and 7 each time but as these values are from user input i wont know what they will be before runtime.
Any help appreciated, thanks in advance !
-----------MY SOLUTION----------------
String values = DateRangePicker1.Value.ToString();
String startDate = values.Substring(0, 8);
String endDate = values.Substring(11, 8);
DateTime date = DateTime.ParseExact(startDate, "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime date1 = DateTime.ParseExact(endDate, "M/d/yyyy", CultureInfo.InvariantCulture);
String newSDate = date.ToString();
String newEDate = date1.ToString();
String finalSDate = newSDate.Substring(0, 10);
String finalEDate = newEDate.Substring(0, 10);
I know this is slightly messy, but is working for me without affecting performance
This rather seems to be a localization issue (based on the fact that you are providing a string that looks like a date)
Is it possible that by just providing the correct date annotation that this would solve your problem?
DateTime.ParseExact(string)
for instance is a method that allows you to create a datetime object from a string, if you tell it what the string format is
example:
DateTime date = DateTime.ParseExact("2/1/2019", "M/d/yyyy", CultureInfo.InvariantCulture);
will provide a datetime object set to the first of febuary 2019. You can then convert the datetime object to a string with:
date.ToString("dd-MM-yy");
output: 01-02-19
Edit: if you have a range of acceptable formats, it is possible to provide an array of formats in string form.
You can use split to get the charachters you dont know.
Like this:
var sepratedInput = input.split('/');
var res= sepratedInput[1] +"/"+sepratedInput[0]+"/"+sepratedInput[2];
Console.write(res);
I have a string that looks like this: myFile{ddmmyyyy}.csv and a C# DateTime object. I need to substitute the correct day/month/year from the DateTime into the string. However the problem lies in the fact that the parameters can be in a different order AND not all of them might be present.
e.g. All of these are valid use cases:
myFile{ddmmyyyy}.csv
myFile{mmddyyyy}.csv
myFile{mmyyyy}.csv
myFile{yyyymm}.csv
Any suggestions/ideas on the regex that I could use to find/substitute these would be greatly appreciated!
EDIT: Just to be clear, I get the actual string that has "mmddyyyy" in there (characters, not the corresponding numbers) where "mm" needs to be substituted for the month number (10 representing October, for example) for the DateTime received.
private static string FormatFilename(string pattern, DateTime dt)
{
return Regex.Replace(pattern, #"\{(.*)\}", match =>
{
string format = match.Result("$1").Replace("m", "M");
return dt.ToString(format, CultureInfo.InvariantCulture);
});
}
Then just call it like this (for example):
string input = "myFile{ddmmyyyy}.csv";
DateTime dt = new DateTime(2013, 1, 4);
string filename = FormatFilename(input, dt);
Update
It is possible to do this without a regex:
private static string FormatFilename(string pattern, DateTime dt)
{
return string.Format(pattern.Replace("{", "{0:").Replace("mm", "MM"), dt);
}
But I think the other version is cleaner and more resilient to input variation.
would \w+\d+.csv work for you?
Just match
#"myFile\d{8}.csv"
And use DateTime.ParseExact or DateTime.TryParseExact to parse it (use the overload that accepts an array of formats)
I have a string variable that stores a date like "05/11/2010".
How can I parse the string to get only the year?
So I will have another year variable like year = 2010.
You can use the DateTime.Parse Method to parse the string to a DateTime value which has a Year Property:
var result = DateTime.Parse("05/11/2010").Year;
// result == 2010
Depending on the culture settings of the operating system, you may need to provide a CultureInfo:
var result = DateTime.Parse("05/11/2010", new CultureInfo("en-US")).Year;
// result == 2010
This should work for you.
string myDate = "05/11/2010";
DateTime date = Convert.ToDateTime(myDate);
int year = date.Year;
If the date string format is fixed (dd/MM/yyyy), I would like to recommend you using DateTime.ParseExact Method.
The code:
const string dateString = "12/02/2012";
CultureInfo provider = CultureInfo.InvariantCulture;
// Use the invariant culture for the provider parameter,
// because of custom format pattern.
DateTime dateTime = DateTime.ParseExact(dateString, "dd/MM/yyyy", provider);
Console.WriteLine(dateTime);
Also I think it might be a little bit faster than DateTime.Parse Method, because the Parse method tries parsing several representations of date-time string.
you could also used Regex to get the year in the string "05/11/2010"
public string getYear(string str)
{
return (string)Regex.Match(str, #"\d{4}").Value;
}
var result = getYear("05/11/2010");
2010
Variant of dtb that I use:
string Year = DateTime.Parse(DateTime.Now.ToString()).Year.ToString();
So i have this DateTime? and what i want to do is to obtain the hour but show it in 24 hours format.
For example:
If the hour is 2:20:23 p.m. i want to convert it to 14:20 and that's it.
I'm working with Visual C#.
Any ideas please, thank you.
I have something like this
public static string FormatearHoraA24(DateTime? fechaHora)
{
if (!fechaHora.HasValue)
return "";
string retornar = "";
//here goes what i need
}
You can get the desired result with the code below. Two 'H' in HH is for 24-hour format.
return fechaHora.Value.ToString("HH:mm");
date.ToString("HH:mm:ss"); // for 24hr format
date.ToString("hh:mm:ss"); // for 12hr format, it shows AM/PM
Refer this link for other Formatters in DateTime.
Using ToString("HH:mm") certainly gives you what you want as a string.
If you want the current hour/minute as numbers, string manipulation isn't necessary; you can use the TimeOfDay property:
TimeSpan timeOfDay = fechaHora.TimeOfDay;
int hour = timeOfDay.Hours;
int minute = timeOfDay.Minutes;
Try this:
//String.Format("{0:HH:mm}", dt); // where dt is a DateTime variable
public static string FormatearHoraA24(DateTime? fechaHora)
{
if (!fechaHora.HasValue)
return "";
return retornar = String.Format("{0:HH:mm}", (DateTime)fechaHora);
}
Try this, if your input is string
For example
string input= "13:01";
string[] arry = input.Split(':');
string timeinput = arry[0] + arry[1];
private string Convert24To12HourInEnglish(string timeinput)
{
DateTime startTime = new DateTime(2018, 1, 1, int.Parse(timeinput.Substring(0, 2)),
int.Parse(timeinput.Substring(2, 2)), 0);
return startTime.ToString("hh:mm tt");
}
out put: 01:01
Another method
var time = DateTime.Now;
string foo = $"{time:HH:mm}";
Where I find this useful is if there is more than just the time in the string.
string bar = $"The time is {time:HH:mm}";
For Ex
You date enter in the various form in textbox
12/Augest/2010
augest/12/2010
2010/12/Augest
and out put is
three textbox First is day show= 12
textbox second is Months show= augest
textbox third is Year show= 2010
To parse/validate against three expected formats, you can use something like below. Given the pattern, once you know it is valid you could just use string.Split to get the first part; if you need something more elegant you could use TryParseExact for each pattern in turn and extract the desired portion (or re-format it).
string s1 = "12/August/2010",
s2 = "August/12/2010",
s3 = "2010/12/August";
string[] formats = { "dd/MMMM/yyyy", "MMMM/dd/yyyy", "yyyy/dd/MMMM" };
DateTime d1 = DateTime.ParseExact(s1, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None),
d2 = DateTime.ParseExact(s2, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None),
d3 = DateTime.ParseExact(s3, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None);
Use DateTime.Parse(String, IFormatProvider) or DateTime.ParseExact to convert the string into DateTime.
Then you can extract the day, month and year using the corresponding properties.
Use DateTime.Parse(s). See MSDN
Then you can get the individual parts of a DateTime structure.
e.g.
DateTime date = DateTime.Parse("some input date string");
string day = DateTime.Day.ToString();
string month = DateTime.Month.ToString();
string year = DateTime.Year.ToString();
date dt date.Parse(txtBox.text);
txtBox1.Text = dt.Day.ToString();
txtBox2.Text = dt.ToString("MMM");
txtBox3.Text = dt.Year.ToString();
date.Parse might throw depending on the string you give it, but then you can fall back by trying to parse it using a different culture.
Edit: Added an M