I use an external API to get some data. Then I do some calculations in Javascript with those data. One field is date in this format: 2015-01-26 18:28:14
Then I have to parse this date. I tried with:
var last = "2015-01-26 18:28:14"
var login = new Date(last).getTime();
But I have an error of Invalid Date. I also tried:
var last = "2015-01-26 18:28:14"
var login = Date.parse(last);
You could try insert the character T between the date and the time.
ECMAScript 5 adds support for ISO-8601 dates and times. ISO-8601 stipulates that timestamps with both date and time should be written 2015-01-26T18:28:14.
Note that parse returns:
the number of milliseconds since January 1, 1970, 00:00:00 UTC
See Date.parse() for more info.
Running your code caused errors for me in firefox too
formatting the date like this resolved the issue
"2015/01/26 00:00:00"
var last = "2015/01/26 18:28:14"
var login = new Date(last).getTime();
if you date is coming back with the '-' you can simply do a replace
var d = "2015-01-26 18:28:14";
var login = new Date(d.replace('-', '/')).getTime();
Related
I'm using Google Apps Script making an API request to get a date. The date, however, is coming back as a number in scientific notation (1.635218706E9) which I'm assuming is in the format of milliseconds from 1970. After converting it from scientific notation to a regular number (1635218706) creating a new javascript date with it the wrong date and year. It should be Oct 25 2021, but instead gives Dec 31 1969.
Am I missing something when creating a new date from the number? And is there a way just have the API respond with a more readable date instead of milliseconds from 1970?
Just in case. I found if you multiply this number by 1000 and feed it to Data object you can get something a little bit more reasonable:
var seconds = 1.635218706E9;
var date = new Date(seconds*1000);
console.log(date); // output: 2021-10-26T03:25:06.000Z
var date_str = [date.getFullYear(), date.getMonth()+1, date.getDate()].join('/')
console.log(date_str); // output: 2021/10/26
It looks like the API gives you seconds.
you can use toLocaleString / toLocaleDateString
so the code is like this
const dates = new Date()
const fullDates = dates.toLocaleString('en-US')
you can read in documentation here :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
I have to convert local date and time to utc format.
Therefore if I have date as 2021-08-11 (YYYY-MM-DD) and time as 2:40 PM, then slot date time should be 2021-08-11T09:10:00.000Z.
I have tried multiple things, but failed
const dateTimeInUTC = moment(
`${formattedDate} ${formatTime}`,
'YYYY-MM-DD HH:mm:ss'
).toISOString();
above code resulted me => 2021-08-10T21:10:00.000Z (which is +5:30 more)
Also, tried following
const formatted = formattedDate + " " +formatTime (2021-08-11 02:40 PM)
const result = new Date(formatted).toISOString();
this gave me
Range error :Invalid Date
However, this works as expected in console, but gives error in mobile.
I tested it now, convert - to / in date format then it will work fine in react native both on browser console and mobile. for more info you can check that link
var isoDateString = new Date('2021/08/11 12:00 pm').toISOString();
console.log(isoDateString);
If you want to use your date format (date witn -) then you to add T instead of space and the time should be on 24 hour scale
like
var isoDateString = new Date('2021-08-11T13:00').toISOString();
this solution will also work for you.
thanks
you can try that
var isoDateString = new Date('2021-08-11 2:40').toISOString();
console.log(isoDateString);
If you want to covert current System Time to UTC then Do :
const dateTimeInUTC = new Date().toUTCString();
console.log(dateTimeInUTC);
Or if you want convert any specific Date-Time to UTC then Do :
const dateTimeInUTC = new Date("October 13, 2000 00:45:00").toUTCString();
console.log(dateTimeInUTC);
For example, I have this string "2020-09-09T21:00:14.114-04:00"
I grab this from my database and in its current form, it is a string. my goal is to have it display
4 PM instead of the long string of jibberish
is it possible to accomplish this?
I was thinking of possibly creating a new date object like
let test = new Date('2020-09-09T21:00:14.114-04:00').
but I'm stuck at the parsing and formatting part. it would be better to have this be done while the current state is a string but I don't think that this would be possible
edit: i would like the desired output to be the hour:minute and then am/pm
ex 10:15pm
You can do that by parsing the date from your database using Date.parse().
Then you can get the time or whatever you need using date.toLocalTimeString() in your case.
let dateUnix = Date.parse('2020-09-09T21:00:14.114-04:00');
const time = new Date(dateUnix).toLocaleTimeString();
console.log(time); // --> "4:00:14 AM"
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
Here's some useful resources MDN Date.parse()
MDN Date.toLocalTimeString()
You can do as following way.new Date() is used to get the current date and time.
var today = new Date();
var time = today.getHours();
if(time>12){
var new_time= time % 12;
}
else{
var new_time= time;
}
I am not so into JavaScript and I have the following problem.
I have a JSON object like this:
{
"start_date": "2017-11-09 06:00:00"
}
Into a JavaScript script executed into the browser I do:
var dateCurrentOriginalForecast = new Date(currentOriginalForecast.start_date);
and it works fine: it creates a new Date object with the value related to 2017-11-09 06:00:00 date.
The problem is that I have to perform this JavaScript script into a Java application using Rhino (a JavaScript implementation that allows to perform JS code into a Java application) and here it cause an error:
TID: [-1234] [] [2017-11-09 11:10:08,915] INFO {org.apache.synapse.mediators.bsf.ScriptMessageContext} - dateCurrentOriginalForecast: Invalid Date {org.apache.synapse.mediators.bsf.ScriptMessageContext}
TID: [-1234] [] [2017-11-09 11:10:08,918] ERROR {org.apache.synapse.mediators.bsf.ScriptMediator} - The script engine returned an error executing the inlined js script function mediate {org.apache.synapse.mediators.bsf.ScriptMediator}
com.sun.phobos.script.util.ExtendedScriptException: org.mozilla.javascript.EcmaError: RangeError: Date is invalid. (<Unknown Source>#137) in <Unknown Source> at line number 137
at com.sun.phobos.script.javascript.RhinoCompiledScript.eval(RhinoCompiledScript.java:68)
at javax.script.CompiledScript.eval(CompiledScript.java:92)
It seems that this date is invalid and it can't create the Date object.
From what I understood reading online the problem should be that old JS or Rhino (maybe the version of JS implemented by Rhino) does not support date of this type and probably I have to convert it in a date format which is fully compliant with ISO 8601
So I think that I have to convert my string 2017-11-09 06:00:00 into something like compliant with ISO 8601 standard.
I can't use third party library.
How can I do it?
Can use Date#toISOString() or Date#toJSON()
let d = new Date('2017-11-09 06:00:00')
console.log(d.toISOString())
console.log(d.toJSON())
//if you want convert date without convert in timezone than
var date = '2017-11-09 06:00:00';
var convertDate = date.replace(" ", "T"); // 2017-11-09T06:00:00
//if you want to convert in date with utc timezone
var date = new Date("2017-11-09 06:00:00").toISOString()
If I've understood your question correctly the problem is not so much that you need a ISO 8601 formatted date, but it is that you need to create a Date object from a date that is not formatted in ISO 8601. I personally would just use regular expression to parse the date into it's parts and then pass them into the Date constructor:
var currentOriginalForecast = {
"start_date": "2017-11-09 06:00:00"
};
var rxParseDate = /(\d{4})-(\d\d)-(\d\d)\s+(\d\d):(\d\d):(\d\d)/;
var dateParts = currentOriginalForecast.start_date.match(rxParseDate);
var year = dateParts[1],
month = dateParts[2],
day = dateParts[3],
hour = dateParts[4],
minute = dateParts[5],
second = dateParts[6];
var dateCurrentOriginalForecast = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
console.log(dateCurrentOriginalForecast);
Since there is no timezone mentioned in the start_date, I'm assuming it is UTC and converting it using Date.UTC and passing the resulting timestamp from that into the Date constructor. If start_date is in local time you would just remove Date.UTC and pass the parameters directly into the Date constructor. I'll also mention the month - 1; that is because the Date constructor (and Date.UTC) expect a 0-based month.
I am trying to get a count on posted item from meteor-mongo matching date periods.
I inserted my posts dates as such.
posts
submitted: new Date()
the dates in the database have the following format.
yyyy-mm-dd 16:16:34.317Z // I do not understand the last part (what format it is)
I have tried this to get match the date of today from the submitted field
var currentDate = new Date();
var dd = currentDate.getDate();
var mm = currentDate.getMonth()+1;
var yyyy = currentDate.getFullYear();
var today = yyyy+'-'+mm+'-'+dd;
Posts.find({submitted: today}).count()
However, the last part is returning 0.
Is it because the last hh,mm,ss part of today is missing? If so, how can I tell meteor-mongoto ignore the time part of date so that I can return that count?
I don't like to deal with JS date objects formats, and i guess you either (I do not understand the last part (what format it is))
Give a try to momentjs package, the documentation its pretty clear.
So on the insert you can have something like.
var today = moment().format(''MMMM Do YYYY, h:mm:ss a'); // April 3rd 2015, 12:17:06 pm
Posts.insert({subbmited:today})
and do a simple find like this.
var endQuery = today..add('days', 3).calendar(); // just an example.
Posts.find({submitted: {$gt: today,$lt:endQuery}})
Here thanks to #Larry Maccherone point we are using $gte (grater than) and $lt (less than), so this works like find me post between the post submitted day and the post submitted dat + 3 days (like you ask managing ranges)
You are storing your submitted date in MongoDB with both time and timezone information. Performing a direct comparison of your currentDate with the submitted date in Mongo will never be true, since your currentDate does not contain time information.
Also you are using a String data type to query the date, which also will not work since you need to use a Date data type. Something like this will work for you:
var today = new Date();
today.setHours(0, 0, 0, 0);
Posts.find({submitted: {$gt: today}})
Which will return all the posts with a date greater than midnight of today's date.
Try something like this
posts.find({"submitted": /.*today*/})