I would like to convert a Javascript date format to ASP.NET date format.
2012-09-10 12:00PM to /Date(1347442050050-0700)/
Because I'm passing it back to the server. I got the ASP.NET format from the request I did on the server, then convert it to Javascript date using moment.js:
moment("/Date(1347442050050-0700)/").format("YYYY-MM-DD hh:mmA");
Is there a way to do this?
I got what i need. If this is somehow wrong please comment.
var test = moment("2012-09-10 12:00PM").valueOf();
var test2 = moment("2012-09-10 12:00PM").format("ZZ");
var test1 = "/Date("+test+test2+")/";
alert( test1 ); // returns /Date(1347206400000+0800)/
var string = moment(test1).format("YYYY-MM-DD hh:mmA");
alert( string ); // returns 2012-09-10 12:00PM
You can add the function to the moment prototype so that it's a little more portable.
http://jsfiddle.net/timrwood/qe8pk/
moment.fn.toASP = function () {
return '/Date(' + (+this) + this.format('ZZ') + ')';
}
If you want to send a date back to an ASP.NET ASMX web service where the RPC method receives a DateTime object, this may be helpful: https://stackoverflow.com/a/12973157/1145963
Related
I am getting a date from my api and the format i get is "2019-04-17T15:04:28"
the date is UTC.
Should the date i get back have the Z at the end or doesn't it matter. Javascript date function will display incorrect if the Z is not there wont it?
Thanks #Esko thanks i think for me the confusion is that in .net core if you change the json serializer options in startup.cs by the following:
AddJsonOptions(opt =>{
opt.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
});
the tool tip in visual studio says yet it doesn't put the Z on and the documentation also doesn't show the Z (https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateFormatHandling.htm)
Instead i am going to try and set a different option
opt.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
If you know the timezone to be constant, you can always just append +0Z00 to your datestring. For example, if the server serializes time into CEST, turn "2019-04-17T15:04:28" into "2019-04-17T15:04:28+0100"
Parsing "2019-04-17T15:04:28" in new Date will parse it as if it's in your local timezone - the meaning of this string depends on what timezone it's parsed in.
Parsing "2019-04-17T15:04:28Z" will parse it in GMT - meaning that no matter what system parses it, it will always refer to the same time.
In other words, "2019-04-17T15:04:28" as a timestamp is ambiguous unless you know the timezone it was recorded in.
I had the similar problem and I found the answer
In my case the DateTime was with Kind Unspecified, in this case the JsonConvert hasn't enough information to add the Z in the end.
You have several options:
Convert it to UTC with ToUniversalTime method
If you're sure you're working with UTC you can add it to general JsonOptions like this:
JsonConvert.DefaultSettings = (() =>
{
return new JsonSerializerSettings
{
Converters = new List<JsonConverter>() {new IsoDateTimeConverter { DateTimeStyles= System.Globalization.DateTimeStyles.AssumeUniversal } }
};
});
if you just want to add the Kind=UTC to current Unspecified Date, you can always write isoConverter like this:
JsonSerializerSettings
{
Converters = new List<JsonConverter>() { new CustomIsoDateTimeConverter() }
};
Where the class will look like this:
public class CustomIsoDateTimeConverter : IsoDateTimeConverter
{
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value is DateTime dateTime && dateTime.Kind == DateTimeKind.Unspecified)
value = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
base.WriteJson(writer, value, serializer);
}
}
I am currently having some challenge in converting String data type to Date type. I used the MarkLogic JavaScript function xdmp.parseDateTime, but I am always getting the error below:
Scenario: Convert "2013-04-21" (string) to 2013-04-21 (date type)
Code:
let targetDateString = "2013-04-21";
let targetDate = new Date();
targetDate = xdmp.parseDateTime("[Y0001]-[M01]-[D01]",
xs.date(targetDate));
Error Info:
XDMP-ARGTYPE: xdmp.parseDateTime("[Y0001]-[M01]-[D01]", xs.date("2013-04-21")) -- arg2 is not of type String
Am I using the right MarkLogic function, supplying the right parameters to it?
Or is there a better way to do it?
And how do I cast a date back to a string data type?
xs.date("2013-04-21") is the xquery date constructor (ported to JS), taking a string and returning an xs:date. xs.dateTime("2013-04-21T00:00:00") would get you an xs:dateTime.
xdmp.parseDateTime can turn a string to xs:dateTime from more formats, the second term is a string: xdmp.parseDateTime("[Y0001]-[M01]-[D01]", targetDateString)
See https://docs.marklogic.com/xdmp.parseDateTime
Converting back to a string is just fn.string(yourdate)
you can directly use the constructor of date class.
var d = new Date("2013-04-21");
console.log(d);
you can even use it with different formats, Ref.
I want to develop a JavaScript function to calculate the activity of users based on the date in the server where the data is stored. The problem is that the date is a string like this:
2013-08-11T20:17:08.468Z
How can I compare two string like this to calculate minor and major time as in the example?
If you want to compare two dates just use this :
var dateA = '2013-08-11T20:17:08.468Z';
var parsedDateA = new Date(dateA).getTime();
var dateB = '2013-06-06T17:33:08.468Z';
var parsedDateB = new Date(dateB).getTime();
if(parsedDateA > parsedDateB) {
// do something
}
Assuming you need to do the comparisons client-side, the best way is to load the dates into Date objects using Date.parse. Then compare them using the functions provided for Date, such as getTime.
Try parse method:
var s = "2013-08-11T20:17:08.468Z";
var d = Date.parse(s);
As I have understood you in the right way, there is a good answer to your question here.
You can also look at this very good Library (DateJS).
If your problem was converting from the Date-String to js-Date look at this Page.
After serializing an object with DateTime field with JavaScriptSerializer, I see that the DateTime field looks like this:
EffectiveFrom: "/Date(1355496152000)/"
How can I convert this string to Javascript Date object?
UPDATE: This answer may not be appropriate in all cases. See JD's answer for an elegant solution that is likely better.
You could just "fix" the output from JavaScriptSerializer on the .Net side of things:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var json = serializer.Serialize(this);
json = Regex.Replace(json,#"\""\\/Date\((-?\d+)\)\\/\""","new Date($1)");
return json;
This would change
EffectiveFrom: "/Date(1355496152000)/"
to
EffectiveFrom: new Date(1355496152000)
Which is directly consumable by Javascript
EDIT: update to accommodate negative dates
EDIT: Here is the Regex line for VB folks:
json = Regex.Replace(json, """\\/Date\((-?\d+)\)\\/""", "new Date($1)")
UPDATE 2016.11.20: With a lot more datetime handling in javascript/json behind me, I would suggest changing the regex to something as simple as
json = Regex.Replace(json,#"\""\\/Date\((-?\d+)\)\\/\""","$1");
The resulting value is valid JSON, and can be converted to a Date object on the javascript side.
It is also worth noting that moment.js (http://momentjs.com/docs/#/parsing/) handles this format happily enough.
moment("/Date(1198908717056-0700)/");
There is an answer that may help you:
Parsing Date-and-Times from JavaScript to C#
If you want to parse datetime string to datetime value with javascript you must use "new Date" like this:
var data = new Date("1355496152000");
var obj = { EffectiveFrom: "/Date(1355496152000)/" };
//parse the Date value and replace the property value with Date object:
var dateValue = parseInt(obj.EffectiveFrom.replace(/\/Date\((\d+)\)\//g, "$1"));
obj.EffectiveFrom = new Date(dateValue);
This is a bit of a hack, but the above seemed inelegant for what I'm trying to achieve, so in the object definition I'm serializing, I did this:
/// <summary>Date of the record retention event or document date.
/// </summary>
public string DateOfRetentionEvent;
[ScriptIgnore]
public DateTime RetentionEventDate
{
get
{
return _retentionEventDate;
}
set
{
_retentionEventDate = value;
DateOfRetentionEvent = value.ToShortDateString();
}
}
The point being that, at least in my use case (deserialization never happens), the JSON doesn't really care what C# is doing with the date value. Adding [ScriptIgnore] to the DateTime value and giving an alternative view for the parser to output should do the trick. It does in my case:
{
"DateToDispose": "1/1/2020",
"DateOfRetentionEvent": "10/1/2014",
"FullRetentionCode": "NR+5",
"RetentionEvent": "NR",
"RetentionPeriod": 5
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Simplest way to parse a Date in Javascript
I understand how do get the data and break it down into it's segments, i.e.
alert( ( new Date ).getDate() );
and
alert( ( new Date ).getFullYear() );
alert( ( new Date ).getFullMonth() );
etc etc.
But how do I do the same but use a date from a html textbox? instead of reading new Date?
The date in the HTML box would be formated as follows
31/10/2012
You could try:
var datearray = input.value.split("/");
var date = new Date(datearray[2],datearray[1] - 1,datearray[0])
If your textbox has proper string format for a date object you can use:
var aDate = new Date($("textbox").val());
However, if you dont write it in the text box exactly as you would in a string passing to the object, you'll get null for your variable.
FYI, I made a plugin that "extends" the Date object pretty nicely and has preformatted date/times that include things like a basic SQL datetime format.
Just go to this jsFiddle, Copy the code between Begin Plugin and End Plugin into a js file and link it in your header after your jQuery.
The use is as simple as above example:
var aDate = new DateTime($("textbox").val());
And to get a specific format from that you do:
var sqlDate = aDate.formats.compound.mySQL;