Dash in date format and get method - javascript

I have asp (classic) script and within javascript code. From database I get date in format yyyy-mm-dd (2010-10-14) and save in variable. Then, I pass this variable to javascript method:
Response.Write("<a href='Javascript: PassDate("&OurDate&","&Val1&","&Val2&");'>Pass</a>")
This method code is:
function PassDate(OurDate, Val1, Val2)
{
window.open("newsite.asp?date="+OurDate+"&val1="+Val1+"&val2="+Val2");
}
When I try get date on new site (newsite.asp) by Request.QueryString("date"), I get calculate value 1996 (2010-10-14 = 1986), instead date '2010-10-14'.
I try various ways to solve this problem, but it still calculate value.
For example, I try replace "-" for ".", but I get error about missing ")".

Use commas instead of dashes. That way, each part will be seen as a separate argument to the JavaScript function.

Have you considered saving the date using the javascript date object and then passing that to your method?
My javascript is a little rusty, but I believe it would be something like the following:
var dateParts = split(OurDate, "-");
var myDate = new Date(dateParts[0], dateParts[1], dateParts[2]);

Related

How to convert UTC time to local time in Javascript

My backend is in Django. I used Django's auto_now_add feature on the model to add the current time when that model was created. For example, I am passing this value to the function: 2019-10-08 09:16:20.666754+00:00.
How to convert this in local time in Javascript? I have not coded JS. So the line's a bit blurry for me.
I tried the following method:
function localize_time(date) {
date = new Date(date);
date = date.toString();
}
Then I saw another SO post to add "UTC", that's not working either. when I am calling a said function from Django's template, it's showing following error:
Uncaught SyntaxError: missing ) after argument list
It's on that function.
In Django's template, I am calling the function like this:
<script type="text/javascript">
localize_time({{ user.created_on | safe}});
</script>
If I don't add safe, then the error is:
Uncaught SyntaxError: Unexpected number
Thanks in advance.
I converted the Django's time in milliseconds using datetime.timestamp method and rest of things worked like magic.
you need to add UTC at the end of your date string.
const date = new Date('2019-10-08 09:16:20.666754+00:00 UTC');
alert(date.toString())

Parsing date in Json Encoded array

I have built a MVC site and I am passing in my model to the view and attempting to use it in some javascript in the view using:
var records = #Html.Raw(Json.Encode(Model));
I am aiming on using these records in a custom calendar object that accepts an object array as a datasource. However, the datasource expects date variables to know where to put appointments etc. I've read that Json does not have any date format of it's own. So, all the dates that are returned from the encode are formatted like:
/Date(1462921200000)/
The object doesn't seem to accept this and nothing is shown on the view. In the posts that I've read they have stated that you can parse the date back into the correct format but this seems to be only on individual values.
My question is: is there an easy way to take the encoded object I've got and parse the dates into the correct format? Or would I have to loop through them in order to do it?
Thanks.
Warning: This answer is opinionated.
The opinionated part is: when you need something done with Json, use Json.Net.
namespace System.Web.MVC
{
public static class HtmlHelperJsonExtensions
{
public string JsonEncode(this System.Web.MVC.HtmlHelper html, object o)
{
var jsonSettings = new Newtonsoft.Json.JsonSerializerSettings()
{
// Here you can apply a LOT of formatting, as a small example regarding dates:
// 1 - formats dates as iso strings (probably what you want)
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
// 2 - formats dates with Microsoft format (what you're experiencing)
//DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat,
// 3 - formats date in a custom format as for DateTime.ToString(string) overload
//DateFormatString = "yyyy-MM-dd"
Formatting = Indented
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(o, jsonSettings);
return html.Raw(json);
}
}
}
Usage:
var records = #Html.JsonEncode(Model);
Refer to the excellent Json.Net documentation here for insights.
Asp.Net MVC application return the dates in the ISO-8601 format by default.
You can convert the value in the client side with a function like this:
function ConvertDate(dateString) {
return new Date(parseInt(dateString.replace("/Date(", "").replace(")/", ""), 10));
}
Or you can use a library like momentjs (https://momentjs.com/docs/#/parsing/asp-net-json-date/):
moment("/Date(1198908717056-0700)/"); // 2007-12-28T23:11:57.056-07:00
Disclaimer: question was not identified as ASP.NET when I composed this answer. I presume the OP is asking for some feature provided by his yet to be disclosed framework. I keep the answer because I think it's valid for manual decoding in vanilla JavaScript.
The format can be parsed with a simple regular expression
var asText = "Date(1462921200000)";
var asDate = null;
var parsed = asText.match(/^Date\((\d+)\)$/);
if (parsed!==null) {
asDate = new Date(+parsed[1]);
}
console.log(asDate);

Validating Date Time In Javascript

I need some help with validating a date time string in Javascript, based on the browser's language.
I can get the datetime format easily enough, for instance if the language is set to pt-BR the format would be
dd/MM/yyyy HH:mm:ss
I tried using something like this:
var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = Date.parseExact($("#theDate").val(), dateFormat);
However x is always Null. I am thinking because Date.parseExact is not able to do times. I need to be able to do this for all browser languages and I would prefer to not use another library. Using Regex is out also since I would need to write so many different expressions.
Does anyone have any suggestions to help me ge on the right track? I am also not against using a webmethod.
I have tried using the following webmethod, which works with en-US but nothing else:
Public Function ValidateDates(ByVal strDate_In As String) As String
Dim theFormat As String = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern() + " " + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern()
Try
Dim d As DateTime = DateTime.ParseExact(strDate_In, theFormat, CultureInfo.CurrentCulture)
Return "true"
Catch ex As Exception
Return "false"
End Try
End Function
You can use Regex to do this:
var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = $("#theDate").val().match(/^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})$/);
console.log(x);
Demo: https://jsfiddle.net/kzzn6ac5/
update
The following regex may help you and improve it according to your need:
^((\d{2}|\d{4})[\/|\.|-](\d{2})[\/|\.|-](\d{4}|\d{2}) (\d{2}):(\d{2}):(\d{2}))$
It matches the following format with /.- and yyyy/mm/dd hh:mm:ss or dd/mm/yyyy hh:mm:ss
Updated demo: https://jsfiddle.net/kzzn6ac5/1 or https://regex101.com/r/aT1oL6/1
Further Regex expressions relevant to date matching can be found here.
JavaScript date objects are deceptively easy, I worked with them in a project and they had a sneaky learning-curve that takes a lot of time to master (as opposed to the rest of JavaScript, which is relative child's play). I recommend letting VB, or really anything else handle it.
But if you want a way to do it in javascript, without Regex (as stated in your question), you could perform string operations on it like this:
try {
var user_input = $("#theDate").val();
var split = user_input.split(" "); // 0: date, 1: time
var split_time = split[1].split(":"); // 0: hours, 1: minutes, 2: seconds
d.setHours(split_time[0]);
d.setMinutes(split_time[1]);
} catch {
// not in a valid format
}
This solution assumes the input is in the correct format, and if an error occurs, it's not. It's not the best way of doing things, but JS Date objects are seriously horrible.

getFullYear is not a function

I am trying to get the age based on two dates: Date of birth and date of visit. Everytime I try to use getFullYear(); in the following manner: I get the error that
var b = getField("dob").value;
var c = b.getFullYear();
I get this error in the console.
b.getFullYear is not a function
2:Console:ExecException in line 2 of function top_level, script Console:Exec
TypeError: b.getFullYear is not a function
2:Console:Exec
undefined
What am I doing wrong? I've tried all sorts of ways to make this work and the only thing that does is I use substring() to get the last 4 digits of the date.
The date is formatted as mm\dd\yyyy.
Thanks!
try var b = new Date(getField("dob").value);
You can check for type of b to be of Date
For Eg:
var b = getField("dob").value;
if(Object.prototype.toString.call(b) === '[object Date]')
{
var c = b.getFullYear();
}
else{
alert("Not valid date");}
In a comment you said
the dob field is a text field formatted as dd/mm/yyyy Is that what you were asking
...and you've tagged your question acrobat, so I'm guessing this is JavaScript running within a PDF, not in a web browser.
On browsers, if you try to parse a string in the form dd/mm/yyyy (say, 03/05/2014), regardless of the locale of the browser (U.S., UK, Spanish, Russian, Japanese), the browser will try to read it as mm/dd/yyyy (American format, month-day-year) first. This is not specified anywhere (certainly not in the JavaScript spec), but it's been true of every browser I've ever tried it on.
If Acrobat does the same thing, and you have the text field formatted as dd/mm/yyyy, you'll run into trouble — is 03/05/2014 May 3rd or March 5th? In the format you're using, it's May 3rd, but in American format it's March 5th.
Unless you want to test Acrobat in multiple locations (or can find a reference promising you how it will parse that string), you'll want to parse it yourself.
If you just want the year at the end, that's fairly simple:
var match = getField("dob").value.match(/(\d{4})\s*$/);
var year = match ? match[1] : undefined;
That'll be a string. If you want to make it a number, you can change the second line slightly:
var year = match ? +match[1] : undefined;
(The + converts match[1], which we know is all digits, to a number.)
If you want the full date, there are several answers here on SO that demonstrate parsing a date with a well-defined format.

Check if date is in given format with Javascript

How can I check if date is in given format or not. It must be function like this
function isInGivenFormat(date,format)
{
//some checking
}
For example, isInGivenFormat("12:45:02","hh:mm:ss") must return true and isInGivenFormat("12:45:02 PM","hh:mm:ss") must return false.
How can I achive this functionality with Javascript/Jquery?
I would urge you to look at the Date.js library. It handles this scenario (and much more).
In particular the parseExact() method solves this problem.
Date.parseExact ( String dateString, String formatStringOrArray ) : Date
Converts the specified string value into its JavaScript Date equivalent using the specified format (string) or formats (array). The format of the string value must match one of the supplied formats exactly.
Examples
Date.parseExact("12:45:02 PM","hh:mm:ss"); // returns null
Date.parseExact("10/15/2004", "M/d/yyyy"); // The Date of 15-Oct-2
var dateCheck = /^\d{2}:\d{2}:\d{2}$/.test(date)
if(!dateCheck){
//not a match
}
You can use the Date.parseExact() function of the date.js library
You need to use the regular expressions. This link could help:
regex in javascript

Categories