Date coming out in a strange format
我有以下代码可行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | <%@ WebService Language="C#" Class="Absences" %> using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Web; using System.Web.Script; using System.Web.Script.Services; using System.Web.Services; public class Absence { public string name; public DateTime from; public DateTime to; public Absence(string m_name, DateTime m_from, DateTime m_to) { name = m_name; from = m_from; to = m_to; } public Absence() { } } [ScriptService] public class Absences : WebService { List<Absence> Absence = new List<Absence>(); SqlConnection connection; SqlCommand command; SqlDataReader reader; [WebMethod()] public List<Absence> GetAbsences(string strDateYear, string strDateMonth, string strDateDay) { var absences = new List<Absence>(); using (connection = new SqlConnection(ConfigurationManager.AppSettings["connString"])) { using (command = new SqlCommand(@"select full_name, from_date, to_date from table1", connection)) { connection.Open(); using (reader = command.ExecuteReader()) { int NameIndex = reader.GetOrdinal("full_name"); int FromIndex = reader.GetOrdinal("from_date"); int ToIndex = reader.GetOrdinal("to_date"); while (reader.Read()) { absences.Add(new Absence(reader.GetString(NameIndex), reader.GetDateTime(FromIndex), reader.GetDateTime(ToIndex))); } } } } return absences; } } |
唯一的问题是日期,它们在JSON数据中以奇怪的格式出现,例如:
如何将日期格式化为以下格式
这是解决方案
1 2 3 4 5 6 7 | var jsondateString ="\/Date(1353456000000)\/".substr(6); var current = new Date(parseInt(jsondateString )); var month = current.getMonth() + 1; var day = current.getDate(); var year = current.getFullYear(); var date = day +"/" + month +"/" + year; alert(date); |
你可以使用moment.js。 它是一个非常灵活的开源库。
A 5kb javascript date library for parsing, validating, manipulating, and formatting dates.
1 | moment("/Date(1198908717056-0700)/").valueOf(); // 1198908717056 |
这应该工作
1 2 3 4 5 6 | var data = {"from":"\/Date(1353456000000)\/"}; var parsedDate = new Date(parseInt(data.from.substr(6))); var curr_date = parsedDate.getDate(); var curr_month = parsedDate.getMonth() + 1; var curr_year = parsedDate.getFullYear(); alert(curr_date +"/" + curr_month +"/" + curr_year); |
工作小提琴 - http://jsfiddle.net/tariqulazam/a2xZM/