0

I have following string in c#,

"2015-9-9,2015-9-10,2015-9-11,2015-9-12,2015-9-13,2015-9-14"

now I want to convert that in a javascript variable like following json format.I want to send to server side to client side in one variable and required to use in javascript varialbe.

var avadates = ["2015-9-9", "2015-9-10", "2015-9-11", "2015-9-12", "2015-9-13", "2015-9-14"];

so,How to convert in Json from C# or any otherways to do that?

0

2 Answers 2

2

This gets every date, add then convert it to string adding the 0 to the month, then merge all the dates:

string toJsonify = "2015-9-9,2015-9-10,2015-9-11,2015-9-12,2015-9-13,2015-9-14";
var dates = toJsonify.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => DateTime.ParseExact(s, "yyyy-M-d", System.Globalization.CultureInfo.InvariantCulture)
                                     .ToString("yyyy-MM-dd"));

var res = "[\"" + string.Join("\",\"", dates) + "\"]";
Sign up to request clarification or add additional context in comments.

6 Comments

this has binded like at client side "["2015-9-9","2015-9-10","2015-9-11","2015-9-12","2015-9-13","2015-9-14","2015-9-15","2015-9-16","2015-9-17","2015-9-18","2015-9-19","2015-9-20","2015-9-21","2015-9-22","2015-9-23"]" so due to starting and ending quotes not working.
it is also required to convert 2015-9-10 to 2015-09-10,need to append zero before month.
@skiskd You mean that the output string should start and end with "?
You mean that the output string should start and end with "? . No it should not have " ...". only in format like ["2015-9-9", "2015-9-10"]
I updated the answer, the output is ["2015-09-09","2015-09-10","2015-09-11","2015-09-12","2015-09-13","2015-09-14"]. Is it correct?
|
0

probably not the most elegant way of achieving what you want but using the JSON.net libaray you can get the results in a J array using the following code.

string sample = "2015-9-9,2015-9-10,2015-9-11,2015-9-12,2015-9-13,2015-9-14";
        List<string> list = sample.Split(',').ToList<string>();

        string json = JsonConvert.SerializeObject(list);
        JArray result = JArray.Parse(json);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.