Angular 6: Invalid time value - javascript

I am trying to get two date and times as a string of numbers (epoch) so I can compare them. One is a new Date():
today = new Date().valueOf();
And one is from an api response in the format:
scheduleDate: "2019-07-22T00:00+01:00"
The issue is I am trying to get the returned date in the correct format. When I try
var scheduleDate = new Date(scheduleDate).toISOString()
console.log("converted date:" + scheduleDate);
I get the error:
Invalid time value
How do I get the returned date into epoch format?
Thanks

Your scheduleDate variable must be undefined. Are you sure it's being assigned properly?
(function() {
//number (milleseconds)
const today = new Date().valueOf();
//string
const scheduleDate = undefined; //"2019-07-22T00:00+01:00";
const scheduleDate2 = new Date(scheduleDate).toISOString()
console.log(typeof today);
console.log(typeof scheduleDate);
console.log("converted date: " + scheduleDate);
}
)();
More worryingly, why are you converting a date string to a date and then back to a string (same value).

You are missed to assign the value
scheduleDate= "2019-07-22T00:00+01:00"
Then try its working
> scheduleDate= "2019-07-22T00:00+01:00"
'2019-07-22T00:00+01:00'
> new Date(scheduleDate)
2019-07-21T23:00:00.000Z
> var scheduleDate = new Date(scheduleDate).toISOString()
undefined
> scheduleDate
'2019-07-21T23:00:00.000Z'
> console.log("converted date:" + scheduleDate);
converted date:2019-07-21T23:00:00.000Z

Related

Trying pass datetime to the api

I am trying to pass the current client local date time to API by using the GET method, getting the error,
UI:
const localDateTime = new Date().toLocaleString();
await fetchDocument(`${process.env.REACT_APP_API_URL}/api/projects/${projectNumber}/${localDateTime}/${currentProjectPhase}`,
setIsBodDownloading,
instance,
history
);
API:
[HttpGet("{projectNumber}/{localDateTime}/{projectPhase?}")]
public async Task<ActionResult> BasisOfDesign(
[FromServices] IDbContextFactory<APIDbContext> serviceScopeFactory,
[FromServices] ICrmProjects crmProjects,
[FromServices] IConfiguration configuration,
[FromServices] IEmployeeContext employeeContext,
string projectNumber,
string localDateTime,
string projectPhase = null,
CancellationToken cancellationToken = default)
{
.....
....
}
I am getting the below error.
{"errors":[{"message":"Either the parameter query or the parameter id
has to be set.","extensions":{"code":"HC0013"}}]}
I cannot use the server time, and I need to use only the client date and time for processing the results. I am looking into this type of string "12-19-2012, 7:00:00 PM"
Could anyone please let me know, Where I am doing wrong with the above code?
this line of code const localDateTime = new Date().toLocaleString(); is producing
7/25/2022, 9:59:46 PM
wich is not valid in URL.
try changing it to a valid form maybe like this :
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = year + "/" + month + "/" + day;
console.log(newdate) // producing valid form to be used in URL like this 2022/7/25
new Date().toISOString() will produce ISO format which the API's generally accept( ISO-8601).
Console.log(new Date().toISOString())
Result:'2022-07-25T22:20:38.413Z'

date assignment from array list to JavaScript variable

I have an Array List myData which holds value like this
[20-01-2018,10-01-2018, 20-02-2018, TASk2, 11-02-2018, 21-03-2018, TASK3, 15-03-2018, 19-04-2018]
am assigning that values to a javascript variable
var start = new Date(<%=myData.get(1)%>);
alert(start) gives output as
Thu Jan 01 1970 05:29:57 GMT+0530 (India Standard Time)
but when i print myData.get(1) gives
10-01-2018
i want the start variable to hold the date value 10-01-2018 alone
can any one tell me where am i wrong.
I have made below modifications.Added a java script function to format the date
as required by me and return it.
step. 1 Iterate the arraylist
2. assign value as argument to a java script function to format it
start=formatMyDate('<%=pertData.get(loopcount+1)%>');
end= formatMyDate('<%=pertData.get(loopcount+2)');
function formatMyDate(myday)
{
alert("entered value"+myday);
var tday = new Date(myday);
alert("processing on value"+tday);
alert(typeof tday);
var dd = tday.getDate();
var mm = tday.getMonth()+1; //January is 0!
var yyyy = tday.getFullYear();
if(dd<10){
dd='0'+dd;
}
if(mm<10){
mm='0'+mm;
}
var ret = dd+'/'+mm+'/'+yyyy;
alert("left value"+ret);
return ret;
}
Now for some values it works and for some it does'nt and gives Invalid date
Sample ouput after running JScript
entered value20-02-2018
processing on valueInvalid Date
What about simply:
const start = myData.get(1);
or
const start = myData[1];
?
The problem is that you do not meet the correct format for the string you hand in when calling
var tday = new Date(myday);
Please have a look at this page. There you can see which format your string must have to receive a valid date object. Which means in your case, that it was useless to push the string through this conversion process using new Date(). Better get your year, month and day directly:
let start = myData[1];
const dd = start.substring(0,2);
const mm = start.substring(3,5);
const yyyy = start.substring(6,10);
const ret = dd+'/'+mm+'/'+yyyy;
alert("left value: " + ret);
return ret;

"invalid date" in javascript when making a date out of Date().getTime()

I have the following Javascript code:
var dateMilliseconds = web3.toAscii(newArray[i]).substring(0, 13)
console.log(dateMilliseconds) // returns 1500282374082
var date = new Date(dateMilliseconds)
console.log(date) // returns invalid date
If I try var date = new Date(1500282374082) instead, it works - how should I be passing the dateMilliseconds variable in properly and what type should it be?
You need to pass this as an integer, and not a string.
You can use the +value trick to convert it into an integer:
var date = new Date(+dateMilliseconds)

How do I get the Monday of the current week?

(function () {
var date = new Date().toISOString().substring(0, 10),
field = document.querySelector('#date');
var day = new Date(date);
var getMonday = day.getDay(),
diff = date.getDate() - getMonday + (getMonday == 0 ? -6:1);
field.value = new Date(date.setDate(diff));
console.log(date);
})();
I am trying to get the Monday of the current date.
I keep getting errors about it and not sure how to resolve it
TypeError: date.getDate is not a function
at index.html:394
at index.html:398
(anonymous) # index.html:394
(anonymous) # index.html:398
Post of so called Duplicate only asks for the how to get the date. My question has similar code but I am getting error messages that was never addressed in the question
You transform the date to string in the first line:
date = new Date().toISOString().substring(0, 10) that is what causes the error... date is no longer a Date object.
--- EDIT: Solution
I would suggest you to either declare an additional variable for any of your later use as ISO string, or to make the conversion after only when output:
For this, I'd suggest add your format to the Date object's prototype
Date.prototype.myFormat = function() {
return this.toISOString().substring(0, 10);
}
Update your initial code like this:
var date = new Date(),
str_date=date.toISOString().substring(0, 10),
field = document.querySelector('#date'),
day = new Date(date),
getMonday = day.getDay(),
diff = date.getDate() - getMonday + (getMonday == 0 ? -6:1);
console.log(date);
console.log(str_date);
console.log(new Date(date.setDate(diff)));
console.log(new Date(date.setDate(diff)).myFormat());
//Now you can update your field as needed with date or string value
field.value = new Date(date.setDate(diff));
field.value = new Date(date.setDate(diff)).myFormat();
If you need it in more places make the getMonday also a function...
Happy coding,
Codrut

Parse dates from Javascript Date Object to regular datetime

How do I convert a date from JS Date Object to php datetime?
The following dates were converted to a Javascript Date Object from php datetimes:
"startsAt": "2015-08-15T10:46:00+00:00",
"endsAt": "2015-08-15T11:46:00+00:00"
converted using this syntax in javascript:
for (var i = 0; i < events.events.length; i++) {
events.events[i].startsAt = new Date(events.events[i].startsAt);
events.events[i].endsAt = new Date(events.events[i].endsAt);
}
startsAt and EndsAt looked like so after the conversion:
startsAt: Date 2015-08-15T11:46:00.000Z
endsAt: Date 2015-08-15T11:46:00.000Z
Now my goal is to do the opposite in javascript (angularjs): Convert from Javascript Date Object to php datetime 2015-08-15T10:46:00+00:00. Any idea would help. Thanks
Just to fix correct an answer below:
var rawDate = new Date();
var parsedDate = [
rawDate.getDate(),
(rawDate.getMonth() + 1), //because getMonth() starts from 0
rawDate.getFullYear()
].join('-');
console.log(parsedDate); // output could be: 19-08-2015 for example
or just call any of the following to convert date object to string:
rawDate.toJSON();
rawDate.toISOString();
You've got to parse it manually doing something like:
var rawDate = new Date();
var parsedDate = rawDate.getDate() + '-' + rawDate.getMonth() + '-' + rawDate.getFullYear();
console.log(parsedDate); // output could be: 19-08-2015 for example
Other possible ways of doing this could be found in here.

Categories

Resources