0

How to convert a String, such as 01 Juni 2015 into DateTime?

I try i, but display error message (as shown below):

enter image description here

Code:

string urlPath = "website";
var values = new List<KeyValuePair<string, string>>
{


};
var response = await client.PostAsync(new Uri(urlPath), new Windows.Web.Http.HttpFormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();

if (!response.IsSuccessStatusCode)
{
    RequestException();
}

string jsonText = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonArray jsonData1 = jsonObject["data"].GetArray();

foreach (JsonValue groupValue in jsonData1)
{
    JsonObject groupObject = groupValue.GetObject();

    string tanggal = groupObject["tgl"].GetString();
    BukuAudio file = new BukuAudio();
    string[] formats = { "d MMM yyyy" };
    var dateTime = DateTime.ParseExact(tanggal.Text, formats, new CultureInfo("id-ID"), DateTimeStyles.None);
    file.Tanggal = n;
    datasource.Add(file);

}

Note:

Date is binding from JSON

Ian
  • 30,182
  • 19
  • 69
  • 107
Rose
  • 613
  • 4
  • 22

3 Answers3

1

it should be MMMM (not MMM), use "d MMMM yyyy" as format.

MMM: is for displaying the three-letter form of the month represented in the DateTime (like "Jan").

MMMM: is for displaying the full month string, properly capitalized. An example is "January

So you could modify your code to

string[] formats = { "d MMMM yyyy" };
var dateTime = DateTime.ParseExact(tanggal.Text, formats, new CultureInfo("id-ID"), DateTimeStyles.None);
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
1

Your format you are specifying is d MMM yyyy while the date you are trying to parse is 01 Juni 2015. These do not match, so it fails the conversion.

To make it work, change your format to dd MMMM yyyy.

MSDN has the list of DateTime format strings: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Steve
  • 9,335
  • 10
  • 49
  • 81
1

You should use four M (MMMM) instead of three M (MMM)since your month is Juni not Jun:

string[] formats = { "d MMMM yyyy" };
var dateTime = DateTime.ParseExact(tanggal.Text, formats, new CultureInfo("id-ID"), DateTimeStyles.None);

It is OK to have single or double d, because your format is 01 Juni ..., but if your format is 1 Juni ..., then you should use single d

Ian
  • 30,182
  • 19
  • 69
  • 107