1

I have many strings like "20120117" and "20120321". I need to convert it in a new string with this format: "2012/01/17" and "2012/03/21". So, there is a way to do this?

I try:

string dateString = string.format("{0:d", "20120321");

and

string dateString = string.format("{0:yyyy/MM/dd", "20120321"); 

and

string dateString = int.Parse("20120321").ToString("yyyy/MM/dd");

I all cases i don't reach my goal. =/

So, i can i do this?

OBS: There is a way to do that without parse to datetime?

Vinicius Ottoni
  • 4,631
  • 9
  • 42
  • 64

8 Answers8

7

You have to parse those values in DateTime objects first.

Example :

DateTime dt = DateTime.ParseExact("20120321", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
var result = dt.ToString("yyyy/MM/dd");

Edit after your comments on other answers: if you don't like parsing because it may throw excepations, you can always use TryParse, like this:

DateTime dt;
bool success = DateTime.TryParseExact("20120321", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt);
if (success)
{
    var result = dt.ToString("yyyy/MM/dd");
}

Edit 2: Using TryParseExact with multiple formats:

DateTime dt;
string[] formats = { "yyyyMMdd", "yyyy" };

bool success = DateTime.TryParseExact("20120321", formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt);
if (success)
{
    var result = dt.ToString("yyyy/MM/dd");
    Console.WriteLine(result);
}

It will produce 2012/03/21 when using "20120321" as input value, and 2012/01/01 when using 2012 as input value.

Shimrod
  • 3,115
  • 2
  • 36
  • 56
6
DateTime.ParseExact("20120321", "yyyyMMdd", CultureInfo.CurrentCulture).ToString("yyyy/MM/dd")

You could parse the string but this method gives you validation without any extra code. Imagine receiving "20120230", "20110229", or any other invalid date.

Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
4

From your comments:

There is a way to do that without parse to datetime?

Yes, absolutely. If you really want to propagate bad data through your system rather than highlighting that it's incorrect, you could definitely use:

// Make sure we'll always be able to get a result whatever the input.
string paddedInput = input + "????????";
string mightBeBadWhoKnows = string.Format("{0}/{1}/{2}",
    paddedInput.Substring(0, 4), // The year, if we're lucky
    paddedInput.Substring(4, 2), // The month, if we're lucky
    paddedInput.Substring(6, 2)); // The day, if we're lucky

But why wouldn't you want to spot the bad data?

You absolutely should parse the data. If you want to be able to continue after receiving bad data having taken appropriate action, use DateTime.TryParseExact. If you're happy for an exception to be thrown, use DateTime.ParseExact. I'd suggest using the invariant culture for both parsing and formatting, unless you really want a culture-sensitive output.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • If the input is like "2012" only? There is a way to do this using only TryParse or something like this? (yes i thought this now...) – Vinicius Ottoni Mar 21 '12 at 14:58
  • @ViniciusOttoni: It's not clear what you're asking, I'm afraid. What do you mean by "if the input is like 2012 only" - what about that situation? I would definitely use `TryParseExact` if at all possible. – Jon Skeet Mar 21 '12 at 15:01
  • 2
    @ViniciusOttoni: You can provide an array of string for the formats value in the `TryParseExact` method. so you can specify "yyyyMMdd", "yyyy" or wathever value you want, if _at least_ one of this format is matching, it will work. – Shimrod Mar 21 '12 at 15:03
  • I posted a regex as a comment to your post, but it is ugly. ParseExact is the most elegant and correct solution. So I don't know why you wouldn't want to use it. – row1 Mar 21 '12 at 15:08
  • I was talking about if the value of the input variable was `2012` only, instead `20120321`. Anyway, thank you! =) +1 to you! ^^ I saw that doesn't exist a better way to do that without `ParseExact` or `TryParseExact` of the Datetime class. – Vinicius Ottoni Mar 21 '12 at 16:45
  • @JonSkeet Jon Can you help me please here? http://stackoverflow.com/questions/9980568/row-number-over-partition-by-xxx-in-linq/9980784#9980784 – Royi Namir Apr 02 '12 at 17:32
3

Use DateTime.ParseExact to convert to a DateTime, then use ToString on that instance to format as you desire.

DateTime.ParseExact(dateString, "yyyyMMdd").ToString("yyyy/MM/dd");

EDIT: using Insert: EDIT2: Fixed bugs :-)

var newString = dateString.Insert(4, "/").Insert(7, "/");
Simon
  • 5,373
  • 1
  • 34
  • 46
2

Just use string operations to insert the slashes:

string input = "20120321";

string dateString =
  input.Substring(0, 4) + "/" +
  input.Substring(4, 2) + "/" +
  input.Substring(6);

or

string dateString = input.Insert(6, "/").Insert(4, "/");
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • If the input is like "2012" only? There is a way to do this using only TryParse or something like this? (yes i thought this now...) – Vinicius Ottoni Mar 21 '12 at 14:59
  • @ViniciusOttoni: You can just check the length to catch that case: `if (input.length == 4) { dateString = input + "/01/01" } else { dateString = ...` – Guffa Mar 21 '12 at 17:04
1

If it's a date, try this:

DateTime.ParseExact("20120321","yyyyMMdd", null).ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)
Botz3000
  • 39,020
  • 8
  • 103
  • 127
1

try this;

string dateString = DateTime.ParseExact("20120321", "yyyyMMdd",
                              null).ToShortDateString(); 
daryal
  • 14,643
  • 4
  • 38
  • 54
0

If your data is always in the same format and if you don't need to validate it, you can use the following snippet to avoid parsing it with DateTime

var strWithInsert =  input.Insert(4,"/").Insert(7,"/");
Adrian Iftode
  • 15,465
  • 4
  • 48
  • 73