我有一个日期时间字符串保存到 cookie,如下所示
DateTime date = DateTime.Now;
LoginDate = date.ToString("u", DateTimeFormatInfo.InvariantInfo).Replace("Z", "");
int sessionTimeout = 1;
DateTime dateExpress = date.AddMinutes(sessionTimeout);
ExpressDate = dateExpress.ToString("u", DateTimeFormatInfo.InvariantInfo).Replace("Z", "");
HttpCookie cookie = HttpContext.Current.Request.Cookies["express"];
if (cookie == null)
{
cookie = new HttpCookie("express");
}
cookie.HttpOnly = false;
cookie.Path = "/";
cookie.Values["express"] = ExpressDate;
Response.Cookies.Add(cookie);
这按预期工作,因为我可以在“应用程序”选项卡中看到 cookie 已正确保存
但是当我从客户端访问它时,它只返回丢失时间部分的日期位。
var current = getCookie("express");
var date = current.split(" ")[0];
alert(date);
我在这里做错了什么?
最佳答案
由于您的express包含express=2017-01-16 09:07:49
,当我们用空格将其分开时,您将得到两个字符串,其中第一个是日期,另一个是日期时间。因此,您必须执行类似的操作才能将日期和时间分开。
var current = getCookie("express");
var date = current.split(' ')[0];
var intime = current.split(' ')[1];
alert(date);
alert(intime);
而 current.split("")[0];
会给你类似 express=2017-01-16
的表达式,因此我相信你应该打破这个再次使用 =
仅获取日期。
否则,如果您正在一个变量中查找日期和时间,您可以执行类似的操作
var current = getCookie("express");
var smDateTime = current.split('=')[1];
alert(smDateTime);
关于javascript - 保存的日期时间丢失时间部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41669286/