How to operate datetime format? · Issue #142 · rpgmaker/NetJSON · GitHub
Skip to content

How to operate datetime format? #142

Description

@zyz

public static string ToJson(this object obj, NetJSONDateFormat dateFormat = NetJSONDateFormat.Default)
{
// 空对象返回
if (null == obj) return string.Empty;

        try
        {
            // 格式设置
            var jsonSetting = new NetJSONSettings
            {
                DateFormat = dateFormat
            };
            return NetJSON.NetJSON.Serialize(obj, jsonSetting);
        }
        catch (Exception ex)
        {
            throw new Exception("JsonHelper.ToJsonFast():" + ex.Message);
        }
    }

public static string ToJson2(this object obj, NetJSONDateFormat dateFormat = NetJSONDateFormat.Default)
{
// 空对象返回
if (null == obj) return string.Empty;

        try
        {
            // 格式设置    
            NetJSON.NetJSON.DateFormat = dateFormat;
            return NetJSON.NetJSON.Serialize(obj);
        }
        catch (Exception ex)
        {
            throw new Exception("JsonHelper.ToJsonFast():" + ex.Message);
        }
    }

public class Test
{
public int Id { get; set; }

    public string Name { get; set; }

    public DateTime CreateTime { get; set; }
}

var test = new Test
{
Id = 1,
Name = "Test",
CreateTime = DateTime.Now
};
var s1 = test.ToJson(NetJSONDateFormat.Default);
var s2 = test.ToJson(NetJSONDateFormat.EpochTime);
var s3 = test.ToJson(NetJSONDateFormat.ISO);
var s4 = test.ToJson(NetJSONDateFormat.JsonNetISO);

        var s5 = test.ToJson2(NetJSONDateFormat.Default);
        var s6 = test.ToJson2(NetJSONDateFormat.EpochTime);
        var s7 = test.ToJson2(NetJSONDateFormat.ISO);
        var s8 = test.ToJson2(NetJSONDateFormat.JsonNetISO);

Result:
s1 = s2 = s3 = s4 = ""
s5 = s6 = s7 = s8

if datetime type format "yyyy-MM-dd hh:mm:ss"
please can you tell me how to operate?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions