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'
Related
We're working on Node-red, where we have a javascript function, where we need to format a datetime looking like this: "2019-08-12T12:10:13Z". The datetime needs to be formatted to "2019-08-12 12:10:13" as we want to store the datetime in our MySQL database as timestamp.
Basically, what we want to do, is to remove the T and Z from the datetime.
This should be fairly easy to do, but we can't find anything on this for javascript.
IMPRORTANT EDIT
Just read that Z stands for UTC, and as we're living in CEST, we want to convert the timezone from UTC to CEST...
If you want to have a special formated Date you have to use library like moment or format it yourself.
const getFormattedDate = (date) => {
return `${date.getFullYear()}-${padNumber(date.getMonth() + 1)}-${padNumber(date.getDate())} ${padNumber(date.getHours())}:${padNumber(date.getMinutes())}:${padNumber(date.getSeconds())}`;
}
const padNumber = (number) => {
return number < 10 ? "0" + number : number;
}
console.log(getFormattedDate(new Date("2019-08-02T05:01:03Z")));
Use the following script to get the current date and time using JavaScript in “Y-m-d H:i:s” format
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
console.log(dateTime);
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
I am using Reactjs and ES6 in the frontend. And GraphQL to make some API calls.
I am getting a key named createDate with a value like this:
2017-03-29T07:19:05-07:00
And I need to format it like this:
03/29/2017 07:19 AM it should show AM or PM.
As this is an string and I am not using any library, I expect someone could guide me to a solution...
You can convert the String to a date object first
var d = new Date("2015-03-25T12:00:00-06:30");
Then define a function constructs the string you want to use for representing the date. For example
function dateToString(d) {
var year = d.getFullYear();
var month = d.getMonth() + 1; // getMonth() returns 0-11
.
.
.
return year + "-" + month "-" + ...;
}
I have a datetime which is from user input. And need to store into database.
The output of date in console.log() in remote server is different from local server.
Data from user input:
ui_date = '2018-05-23';
ui_time = '10:00'; // literally meant for 10 oclock
//.... i manage to concatinate ui_date and ui_time and convert to ISO datetime
Now...
Output from local server
console.log(myDate.toISOString());
// outputs: 2018-05-23T02:00:00.000Z
// This is correct UTC since I'm in philippines and the offset is +8
// Localserver automatically convert it to UTC
Output from remote server
console.log(myDate.toISOString());
// outputs: 2018-05-23T10:00:00.000Z
// This is wrong because it is in local time not UTC
It seems remote server cannot convert this datetime into UTC.
Does anyone have an idea about this?
UPDATE
showing the actual code:
By the way I'm using node.js as a server.
Input from user:
{
"date": "2018-05-23",
"time": "10:00"
}
my route:
router.post('/test_datetime', function(req, res, next) {
console.log(req.body.date);
console.log(req.body.time);
var date = req.body.date;
// get the date, month and year
var dd = new Date(date).getDate();
var mm = new Date(date).getMonth();
var yy = new Date(date).getFullYear();
// get the hour and min from "10:00" and convert to number
var hour = parseInt(req.body.time.substr(0, 2));
var min = parseInt(req.body.time.substr(3, 4));
// constructed datetime
var datetime = new Date(yy, mm, dd, hour, min).toISOString();
console.log(datetime);
});
local server output of datetime:
2018-05-23T02:00:00.000Z
Remote server output of datetime:
2018-05-23T10:00:00.000Z
The problem is your construction of the JavaScript Date because the method you use doesn't take in to account the client's offset to UTC.
Creating a new date from the date string, as your code does initially, will assume the date (and time) is local.
Then just setting the hours and minutes on that date will keep everything in sync.
let date = '2018-05-23';
let time = '10:00';
// parse the date and time using the local timezone info
let d = new Date(date + ' ' + time);
// Generate the UTC ISO string
let isoDateTime = d.toISOString();
console.log(isoDateTime);
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.