I have the following string "2017-2" and I need to format it as "2017-02".
var period = "2017-2";
var periodFormatted = String.Format("{0:0000-00}", period);
periodFormatted returns "2017-2"
What is the correct syntax to get the period formatted as "2017-02"?
string.Format won't know (or care) that your string contains numbers so you cannot directly format like that. You could split up the string and parse the last part as a number though. For example:
var period = "2017-2";
var parts = period.Split('-');;
var periodFormatted = $"{parts[0]}-{int.Parse(parts[1]):D2}";
However, you should probably have the period value as a proper DateTime object (or a custom type representing the year and month values) in the first place, that would have made the formatting trivial.
You can parse the input-string as DateTime and format it in a second step.
string period = "2017-2";
DateTime temp = DateTime.ParseExact(period, "yyyy-M", CultureInfo.InvariantCulture );
string result = temp.ToString("yyyy-MM");
Note: M defines the month without leading 0 and MM is always 2 digit month.
Reference: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
Related
I have two objects of type string, where I retrieve a date in dd/MM/yyyy format, I need to format this date I'm getting to show only month and year, in order to use this object in a groupby to group records by month. I'm doing it as follows, retrieving the date in another object to apply the formatting:
//Object where I retrieve the date with dd/MM/yyyy normally
public string DataCupom { get; set; }
//Object where I retrieve the value of DataCupom and I'm trying to apply the formatting
public string DataCupomAgrupadoMes { get { return String.Format("{MM:yyyy}", DataCupom); }
How can I apply String.Format correctly to retrieve only month and year?
A string is just a sequence of characters. It has no "date" or "time" semantics. Thus, attempting to format a sequence of characters (sucha as the DataCupom string) like it being some data type representing dates or time is not going to work.
In your case, one of the simplest approaches would probably be splitting the DataCupom string using '/' as separator, and then assemble the new required string from those parts of the split which represent month and year.
var parts = DataCupom.Split('/');
return $"{parts[1]}:{parts[2]}";
You can try parsing dateString to DateTime and then format.
DateTime dateTime = DateTime.Parse(dateString);
dateTime.ToString("MM/yyyy");
String.Format() uses numeric placeholders:
return String.Format("{0:MMyyyy}", DataCupom);
Where the 0 in the format string means to look at the first additional argument position for the value.
You can also use interpolation:
return $"{DataCupom:MMyyyy}";
or a simple ToString() call:
return DataCupom.ToString("MM:yyyy");
I have to parse date string in C#. The dates are all ensured to start with year, month, day. But I do not know what dividers will be between the 3 parts.
Additionally the date string may also include a time part after the date.
Basically as long as the format has the year first, month second, and day third, I should parse it as a valid date regardless of which dividers are used and whether a time is included. Any other date formats should be rejected as invalid.
I can not figure out how to do this without writing a long if/else.
How do I parse a string into a C# datetime object, given the restrictions mentioned?
You can check the length of the input string is at least 10 characters, and if it is, work out what the separator should be by looking at the 5th character in the string.
Then you can use the separator to construct a format string that you pass to DateTime.TryParseExact() to parse the date. You also have to truncate the date string to 10 characters to ignore any date part at the end.
An example implementation looks like this - it returns null if the date didn't parse; otherwise, it returns the correctly parsed date:
public static DateTime? ParseDateWithUnknownDivider(string dateStr)
{
if (dateStr.Length < 10)
return null;
char divider = dateStr[4];
if (DateTime.TryParseExact(
dateStr.Substring(0, 10),
$"yyyy\\{divider}MM\\{divider}dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime result))
return result;
return null;
}
Note that this ignores the time part and will always return the time part as 00:00:00. If that's not what you meant, you will need to specify in your question what the time part would look like. For example, would it be separated from the date part by a space? And would it always be hh:mm:ss? And would it be 24hour clock?
try this code
string yourDateTimeString = ....;
string format="yyyy/MM/dd";
var dt = DateTime.ParseExact(yourDateTimeString,format,null,System.Globalization.DateTimeStyles.AssumeLocal);
i have a string like "14-Nov-2014" , i want to convert this string to this 14.11.2014 format.
after converting i want to add 14 days to above date.
given date is not Datetime format.
Old date="14-Nov-2014"
new date=14.11.2014
is there any way to do in c#?
Assuming,
var myString = "14-Nov-2014";
First parse the string, most likely using DateTime.ParseExact. Assuming a few things about the format you have, you could do the following. Note you most likely should specify the proper culture for the third argument:
var dateTime = DateTime.ParseExact(myString, "dd-MMM-yyyy", null);
Then you can add 14 days to it easily:
var dateTime = dateTime.AddDays(14);
To get a new string in a different format just use ToString with a format string. For example:
var myNewString = dateTime.ToString("d.MM.yyyy");
I need to store DateTime in int. So I tried below codes
Int64 n = Int64.Parse(DateTime.Today.ToString("dd-MM-yyyy"));
or
Int64 twoday_date=Convert.ToInt64(System.DateTime.Today.ToString("dd-MM-yyyy"));
but its showing error:
Input string was not in a correct format.
Where is the error?
Just use DateTime.Ticks instead - there's absolutely no reason to start converting to and from strings here.
long ticks = DateTime.Today.Ticks;
// Later in the code when you need a DateTime again
DateTime dateTime = new DateTime(ticks);
Note that this will use the local date - if you're trying to retain a global timestamp, you should use DateTime.UtcNow instead of DateTime.Today.
If you really need int instead of long, you probably ought to translate and scale, e.g. to seconds since the Unix epoch.
You could either store the milliseconds from a certain point in time (that you define), or you could use a format such as yyyyMMddhhmmss (and fff if you want more precision).
The original question asks where is the error? within:
Int64 n = Int64.Parse(DateTime.Today.ToString("dd-MM-yyyy"));
The ToString(...) method generates a string representation of the date time value. In this case its argument, the string "dd-MM-yyyy" gives the format of the string to be generated. So today that will generate the string "11-01-2014". The Int64.Parse(...) attempts to parse its argument string as an integer, but here it has a mix of digits and hyphens. Hence it throws an exception.
Understanding these sort of problems can be tricky. One technique is to break the statement into smaller pieces and understand each of them in turn. When the problem is resolved the corrected pieces can be assembled into a single statement if desired. In this case the statement could be split to be:
string s = DateTime.Today.ToString("dd-MM-yyyy");
Console.WriteLine("The date string is '{0}'", s);
Int64 n = Int64.Parse(s);
Then use either a debugger or the WriteLine shown to show the value in s. Note that the WriteLine encloses the displayed value of s in quotes so that the presence or absence of spaces, newlines and other unexpected characters can easily be detected.
// the local utc offset is +2:00
public class Program
{
public static void Main(string[] args)
{
// code executed in timezone GMT+2:00
long ticksUtc = DateTime.UtcNow.Ticks;
Console.WriteLine("{0:d}",ticksUtc);
DateTime _todayUtc = new DateTime(ticksUtc);
Console.WriteLine("{0}",_todayUtc);
// get local date time from Utc time
Console.WriteLine("{0}",_todayUtc.ToLocalTime());
Console.WriteLine();
long ticksLocal = DateTime.Now.Ticks;
Console.WriteLine("{0:d}",ticksLocal);
Console.WriteLine("{0:d}",ticksLocal-ticksUtc);
DateTime _todayLocal = new DateTime(ticksLocal);
Console.WriteLine("{0}",_todayLocal);
// get the utc time from _todaylocal time
Console.WriteLine("{0}",_todayLocal.ToUniversalTime());
}
}
Any ideas?
I can't come up with any.
I have a list of dates I'm loading in from a csv file and they are saved as all integers, or rather a string of integers (i.e. Jan 1, 2009 = 1012009)
Any ideas on how to turn 1012009 into 1/01/2009?
Thanks!
Since the date is stored as a string, you may want to use ParseExact:
DateTime date = DateTime.ParseExact("28012009", "dMMyyyy", null);
ParseExact will throw an exception if the format doesn't match. It has other overloads, where you can specify more than a single possible format, if that is required. Note that here provider is null, which uses the current culture.
Depending on style you may wish to use TryParseExact.
int date = 1012009;
var month = date / 1000000;
var day = (date / 10000) % 100;
var year = date % 10000;
var formatted = new DateTime(year, month, day).ToString();
This assumes month-day-year; if the numbers are day-month-year, I’m sure you’ll be able to swap the month and day variables to accommodate that.
If you want to customise the date format, you can do so as described in:
Standard Date and Time Format Strings
Custom Date and Time Format Strings
Let 10102009 be dateInt.
string dateString = dateInt.ToString();
int l = dateString.Length;
dateString = dateString.Insert(l-3,"/");
dateString = dateString.Insert(l-6,"/");
You should now have 1/01/2009 in dateString.. You can also try the ParseExact function..