Parse to string for data before sending request - javascript

I know the data before sending will be parsed to string from any type. So where is this process done and how does it happen?
I had this question when I had a problem regarding the format for a Date type in javascript. Specifically, I want to send data that has a field of type Date and I want to format it before sending (example: 29-12-2022). However, I always get a result like 2022-12-29T17:00:00.000Z.
I can convert the interface of data from Date to String. However, I don't want to do that

You should use functions provived default by Date class:
Use toLocaleDateString function
const d = new Date();
let text = d.toLocaleDateString();
console.log(text);
Manually concatenate date, month, year strings:
let d = new Date();
let mm = d.getMonth() + 1;
let dd = d.getDate();
let yy = d.getFullYear();
console.log(`${dd}-${mm}-${yy}`);

Related

How to compare current Hours with a hour string JavaScript

I have attribute string Time:"10:50" response in JavaScript.
How to compare only hour of string with hour of system.
E.g: if 10=10 then run code in function.
Please help. thanks
You should wrap the string into a date object and use the getHours() function on the date object. something like
//in the oldDate, pass the string as params to the date constructor
let oldDate = new Date("date string")
//construct this one without a parameter and it will use the system time
let systemDate = new Date()
if(oldDate.getHours() == systemDate.getHours())
But if you are quite certain that the response is of the form "10:50" then this will be the better option
let time = "10:50"
let h = parseInt(time.split(":")[0])
let systemDate = new Date()
if(h == systemDate.getHours())
Create a Date object: let dateTime = new Date();
Get the current hour: let hour = dateTime.getHours();
Compare it with your desired object.

How can I get a string date in the format "2016-07-06T10:57Z" from Date() and toISOString

I need to get a date in this format:
2016-07-06T10:57Z
Using this code I have been able to get a date in a format somewhat like I need:
var isoDate = new Date().toISOString();
2016-07-06T08:46:08.127Z
But is there a way I can remove the seconds and fraction of seconds from the date so it appears exactly like the date: "2016-07-06T10:57Z" ?
You will always want to remove the last 8 characters ('Z' included) thus you can use a function like slice
isoDate = isoDate.slice(0, -8); //Remove seconds + fractions + Z
isoDate += "Z"; //Add back the Z
You can use this way because the format returned by toISOString() will always be
YYYY-MM-DDTHH:mm:ss.sssZ
Please try
var isoDate = new Date().toISOString();
var pos = isoDate.lastIndexOf(':');
var datePart1 = isoDate.substring(0,pos);
var datePart2 = isoDate.substr(-1, 1);
var dateStr = datePart1+datePart2;
console.log(dateStr);

How do I pass the JSON date value from a textbox and convert it in Javascript?

I'm returning a date to a text box using JSON, this means my date is returned as a string like this:
/Date(1335205592410)
Can anyone tell me how I can access this date from my textbox and convert it to a useable date format i.e. DD/MM/YYYY There are many guides online but most of them suggest using substr(6), with my value being in a textbox I'm not sure how I'd use that approach. I access my textbox like so:
function dateChange() {
var date_box = document.getElementById('date').value;
...
... Code to populate textbox ...
...
}
The textbox is a generic html textbox, when the above function runs it populates it with the JSON date string.
<input id="date" name="date" />
I need help getting the date value from the textbox and then converting it to a useable date. Can anyone help me out?
Many thanks
Does this work ok?
var date = new Date(1335205592410);
var day = "0" + date.getDate();
var month = "0" + date.getMonth();
var year = date.getFullYear();
var formattedDate = day.substr(-2) + '/' + month.substr(-2) + '/' + year;
alert(formattedDate);
Microsoft .Net handles this date format, you can overcome by gettings the miliseconds inside de Date string.
implementation
var convertMSDate = (function() {
var pattern = /Date/,
replacer = /\D+/g;
return function(date) {
if (typeof date === "string" && pattern.test(date)) {
date = +date.replace(replacer, "");
date = new Date(date);
if (!date.valueOf()) {
throw new Error("Invalid Date: " + date);
}
}
return date;
}
}());
usage
var date = '/Date(1335205592410)';
console.log(convertMSDate(date));
// use ISO 8601 format
date = convertMSDate(date);
console.log(date.toISOString());
// get date parts
var year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate();
console.log([day, month, year].join('/'));

converting json results to a proper date - javascript

Hi i am trying to convert a json date back to a normal dd/mm/yy date.
How can i convert the Customer.DateOfBirth dd/mm/yy from a json date back to a normal date?
Here my code?
// parse the date
var Birth = Customer.DateOfBirth;
if (Birth != '') {
// get the javascript date object
Birth = DateFromString(Birth, 'dd/MM/yyyy');
if (Birth == 'Invalid Date') {
Birth = null
}
else {
// get a json date
Birth = DateToString(Birth);
//REPLACE JSON DATE HERE WITH NORMAL DATE??
}
}
Any suggestion would be great.
Thanks
If you can change the JSON representation to yyyy/mm/dd then you can directly convert it using
Birth = new Date(Birth);
If you have to use the current format, then you have to do some manual parsing
Extract the day/month/year parts and create a string in the expected format
var parts = Birth.split('/'),
day = parts[0],
month = parts[1],
year = parts[2],// you need to find a way to add the "19" or "20" at the beginning of this since the year must be full for the parser.
fixedDate = year + '/' + month + '/' + day;
Birth = new Date(fixedDate);
You can create a Date object from mm/dd/yyyy string, so if your string is ordered dd/mm/yyyy you'll either get Invalid Date error, or, possibly worse, create a Date object with wrong date (Januray 10th instead of October 1st).
So you need to swap the dd and mm parts of your string before passing it to the Date constructor:
var datestr = Customer.DateOfBirth.replace(/(\d+)\/(\d+)\/(\d+)/,"$2/$1/$3");
Birth = new Date( datestr );
You could also pass a string in yyyy/mm/dd order:
var datestr = Customer.DateOfBirth.split('/').reverse().join('/');
Birth = new Date( datestr );

how to parse milliseconds into date in javascript

i am getting stucked to convert date from ms (receiving from json)
i was recieving the date in json in format below
/Date(1355250600000)/
so that i converted it into ms --->
var d = response.ContributionsDate.replace("/", "").replace("/", "").replace("Date(", "").replace(")", "");
so now its d = 1355250600000
to convert i tried the code below--->
var date = new Date(d);
alert(date);
but did not work (invalid date), if anyone have any idea about date parsing, help me
d is a string, not a number.
Try
var date = new Date(+d);
instead.
The prefix + causes coercion to a number.
Incidentally, you can simplify your replace operations to
var d = +response.ContributionsDate.match(/^\/Date\((\d+)\)\/$/)[0];

Categories