Say you have a string 5/9/2010 and you want to rearrange it to read 2010/5/9. How would you go about doing that?
I want to sort a list by a string that happens to be a date. While I could make it into a date, I want to stick with a string, if possible because the time part of the datetime is hard to eliminate. (This is being used in an sqlite database for a Unity3d App.)
Forgive me if this is a duplicate.
If you can guarantee that the string will always be the same input format, you can split the string on the /:
string input = "5/9/2010";
string[] inputSections = input.Split('/');
string output = string.Format("{0}/{1}/{2}", inputSections[2], inputSections[0], inputSections[1]);
Working Fiddle
My code is very verbose, you can certainly simplify it for your needs. I would also utilize the string inerpolation feature of C# 6 if it is available to you:
string input = "5/9/2010";
string[] inputSections = input.Split('/');
string output = $"{inputSections[2]}/{inputSections[1]}/{inputSections[0]}";
I would recommend parsing the date, in the off chances that the input date is not exactly in the format you were expecting, but was indeed a valid date. This is the situations parsing is for.
CultureInfo us = CultureInfo.GetCultureInfo("en-US");
string input = "5/9/2010";
DateTime date = DateTime.Parse(input, us);
Console.WriteLine(date.ToString("yyyy/MM/dd", us));
You can test here
Related
This question already has answers here:
C# DateTime to "YYYYMMDDHHMMSS" format
(18 answers)
Closed 5 years ago.
I developing a xamarin form app and I am assigning the current date time as a Filename for image. Currently the image is saved as "7202017 53150 PM.jpg". I want it to be saved like this "720201753150PM.jpg". How can I remove the space between the date and time?
I tried like below but it did not work.
string _imagename = DateTime.Now.ToString();
_imagename.Replace(" ", string.Empty);
Actually the String.Replace() Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string(in short it won't change the actual string) So you need to assign the result to another variable. And perform the replace operation there.
But Why you go for another replace? whynot use .ToString() like the following?
string format = "Mddyyyyhhmmsstt";
string _imagename = String.Format("{0}.jpg",DateTime.Now.ToString(format))
You need to assign the new value as string is immutable:
string _imagename = DateTime.Now.ToString();
_imagename = _imagename.Replace(" ", string.Empty);
This is fastest way I know:
Regex.Replace(_imagename, #"\s+", "")
Looking at your string ill also suggest replace spaces with a empty string. And you could do it by applying built in Replace method:
string _imagename = DateTime.Now.ToString();
_imagename = _imagename.Replace(" ", string.Empty);
If you want to order by file name I'd suggest to use a notation like yyyyMMddHHmmss. That way, with increasing date/time the sort order will also increase.
Other than that, strings are immutable in c#. Thus calling Replace does not change the original string. You need to assign the result to your variable as #Romano Zumbé pointed out.
You can just use a format string like the following (including the sorting suggestion):
string imagename = $"{DateTime.Now:yyyyMMddHHmmss}.jpg";
otherwise it would be:
string imagename = $"{DateTime.Now:Mddyyyyhmmsstt}.jpg";
I have a date range come like this,
string ActualReleaseDates ="7/8/2016, 7/9/2016, 7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
string NewsReleasedDate ="07/11/2016";
I want to check NewsReleaseDate is inside the ActualReleaseDates
But in the following code it return as a false.
if (ActualReleaseDates.Split(',').Contains(NewsReleasedDate.TrimStart(new Char[] { '0' })))
{
//some code here
}
The immediate problem is that after splitting your ActualReleaseDates string, there isn't an entry of "7/11/2016"... instead, there's an entry of " 7/11/2016"... note the space.
But more fundamentally, just trimming the start of NewsReleasedDate won't help if the value is something like "07/08/2016"... what you should be doing is handling these values as dates, rather than as strings:
Split ActualReleaseDates by comma, then parse each value (after trimming whitespace) in an appropriate format (which I suspect is M/d/yyyy) so that you get a List<DateTime>.
Parse NewsReleasedDate in the appropriate format, which I suspect is MM/dd/yyyy, so you get a DateTime.
See whether the parsed value from the second step occurs in the list from the first step.
(I'd personally recommend using Noda Time and parsing to LocalDate values, but I'm biased...)
Fundamentally, you're trying to see whether one date occurs in a list of dates... so make sure you get your data into its most appropriate representation as early as possible. Ideally, avoid using strings for this at all... we don't know where your data has come from, but if it started off in another representation and was converted into text, see if you can avoid that conversion.
The white space problem. You can use trim() and ' 7/11/2016' will be '7/11/2016'
var ActualReleaseDates = "7/8/2016, 7/9/2016, 7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
var NewsReleasedDate = "07/11/2016";
var splitActualReleaseDates = ActualReleaseDates.Split(',').Select(x => x.Trim());
if (splitActualReleaseDates.Contains(NewsReleasedDate.TrimStart(new Char[] { '0' })))
{
}
You can use linq to convert your strings into DateTime objects and compare them instead of strings
string ActualReleaseDates ="7/8/2016,7/9/2016,7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
string NewsReleasedDate ="07/11/2016";
var releaseDates = ActualReleaseDates.Split(',').Select(x => DateTime.Parse(x));
var newsReleased = DateTime.Parse(NewsReleaseDate);
if (releaseDates.Contains(newsReleased))
{
//some code here
}
please note that DateTime is parsed respectively to the current Culture. You can use DateTime.ParseExact if you want to specify exact date format.
You can Prase to DateTime before doing the query like this:
(I think this is the most accurate and guaranteed way to compare dates)
Func<string, DateTime> stringToDate = s => DateTime.ParseExact(s.Trim(), "M/d/yyyy",
CultureInfo.InvariantCulture);
DateTime newReleaseDateTime = stringToDate(NewsReleasedDate);
bool result = ActualReleaseDates.Split(',').Select(x => stringToDate(x))
.Contains(newReleaseDateTime);
It returns false because of the date 07/11/2016 stored in NewsReleasedDate is stored as string with a '0' at the begining. And in the ActualReleaseDates string you have white spaces between the ',' and numbers.
Try to rewrite theese strings like this :
ActualReleaseDates ="7/8/2016,7/9/2016,7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016"; // white spaces removed.
and the variable like this :
NewsReleasedDate ="7/11/2016"; // 0 removed
This is my code example :
string ActualReleaseDates = "7/8/2016,7/9/2016,7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
string NewsReleasedDate = "7/11/2016";
string[] dates = ActualReleaseDates.Split(',');
Console.WriteLine(dates.Contains(NewsReleasedDate));
This is not the best way to compare dates, you can use Date class which is usefull to do this kind of comparations.
I have a string that I would like to format the same way I would a numeric value.
Ex:
int num = 2;
string option = num.ToString("000");
Console.WriteLine(option);
//output
//002
But the only way I can think to format it is to parse it as an int, then apply the ToString("000") method to it.
string option = "2";
option = int.Parse(option).ToString("000");
Is there a better, more direct way to do this?
No, there is no built-in mechanism to "format" a string as if it were a number. Some options:
Use string functions (Pad, Length, Substring) to determine what characters should be added
Parse to a numeric type and use ToString with numeric formatting strings
Use a reqular expression to extract the digits and generate a new string
There's not one "right" answer. Each has risks and benefits in terms of safety (what if the string does not represent a valid integer?), readability, performance, etc.
Would this suit your requirement?
string x = "2";
string formattedX = x.PadLeft(3, '0');
Console.WriteLine(formattedX); //prints 002
I have a string that contains a date & time in some format. For example:
13:53:56 20.08.2014
This string is parsed from a file that user uploads to my service. The exact date & time format is not known. It can change to pretty much any date & time format you know. I do not have a list a expected formats or anything like that.
I want to develop an algorithm that somehow extracts the format from the initial string and applies it to, say, DateTime.Now.
Is there any way to do this simply and elegantly?
If you know the list of expected formats, then define them and use DateTime.TryParseExact() to find out the matching format of your input string. Once you have the matching format, you can simply use the matching format with DateTime.Now.ToString(format).
If this is a web application, perhaps you can "cheat a bit" by sniffing the user's regional settings before they input the string.
The MSDN article "How to: Display Localized Date and Time Information to Web Users" has useful information.
Inspired by a good suggestion by Mani, I've created the following extension method for my needs:
public static bool TryFormatLike(this DateTime dateTime, string another, out string result)
{
var allCultures = CultureInfo.GetCultures(CultureTypes.AllCultures | CultureTypes.UserCustomCulture | CultureTypes.ReplacementCultures);
foreach (var culture in allCultures)
{
var allPatterns = culture.DateTimeFormat.GetAllDateTimePatterns();
foreach (var pattern in allPatterns)
{
DateTime parsedAnother;
if (DateTime.TryParseExact(another, pattern, culture.DateTimeFormat, DateTimeStyles.AllowWhiteSpaces, out parsedAnother))
{
result = dateTime.ToString(pattern);
return true;
}
}
}
result = string.Empty;
return false;
}
You can use it like that:
string formattedNow;
if (DateTime.Now.TryFormatLike("13.02.2015 16:14:43", out formattedNow))
{
Console.WriteLine(formattedNow);
}
This will print
10.03.2015 23:37:08
Unfortunately, some date & time formats cannot be parsed by all patters in all cultures (for instance, string 16:14:43 13.02.2015 will not be parsed).
Anyway, thank you for your comments & answers. Maybe this method will be helpful to someone.
Is there an easy way to check if a format string is valid? For example the following is code that we use to test a number format string;
public static bool IsValidFormatStringNumber(string FormatString)
{
try
{
const decimal number = 0.056m;
var formattedNumber = number.ToString(FormatString);
return formattedNumber.Length > 0;
}
catch
{
return false;
}
}
We're trying to catch an exception or determine if the resulting string has no length. This test fails however as a format string of "hsibbur" (Any rubbish) results in a string of "hsaibbur", which has length.
We want to do the same test for Percent and Date format string.
If you just want to check for standard format strings, just check that your format strings are part of that list.
If you want to check for custom format strings (that are not "Other" or "Literal strings"), you can probably craft a regex to do it.
Other than that, since format strings can be arbitrary strings, I don't think validation even applies.
If FormatString is equal to formattedNumber, that could be another case for returning false.