How to parse string to date with hour in JavaScript? - javascript

I've got string with date
var day = '2016-04-20'
And i want to parse it to 2016-02-01 23:59:59 because when i'll send this string as a query to database. Then is recognize as 2016-04-20 00:00:00.
I know that i could sent it like this: day+' 23:59:59' however it looks unprofessional ;)
#EDIT
I think good idea would be: Date.parse(day) + 1 however Date.parse return the number of milliseconds between January 1, 1970 and the day.

you can do it in mysql date format like this
SELECT DATE_FORMAT(date,'%y:%m:%d %T:%f')
e.g date is '2016-04-20'
then
SELECT DATE_FORMAT('2016-04-20','%y:%m:%d %T:%f')

This...
var day = '2016-04-20'
var mydate = new Date(day);
mydate.setMinutes(mydate.getMinutes() - 1);
var mydatestring = mydate.toISOString().slice(0, 10) + " " + mydate.toISOString().slice(11,19);
...however be VERY careful as JS on the clients machine can very often be different to the server time, even in the same country! so don't expect the times to be 100% correct
UPDATED - first version missed the point of the question

Related

Issues parsing a string-date React/JS

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;
}

JavaScript Date() differs when timezone changes

I need to convert my date to mm-dd-yyyy format. So I used a method like this:
var dt=new Date(2016-06-21);
var ddte='';
ddte=(("0" + (dt.getMonth() + 1)).slice(-2))+"-"+(("0" + dt.getDate()).slice(-2))+"-"+dt.getFullYear();
It works fine in my local timezone (GMT+05:30). But when I change my timezone to GMT -5:00, it gives the wrong result: 06-20-2016. The result I want is 06-21-2016.
Can anyone please explain the problem?
How can I get the correct result?
Is it a bug?
Your date passed to Date() constructor will be treated as UTC time zone. Getting the time with Date.getMonth() will get your local time zone. You're probably looking for Date.getUTCMonth().
var dt=new Date("2016-06-21");
var ddte='';
ddte=(("0" + (dt.getUTCMonth() + 1)).slice(-2))+"-"+(("0" + dt.getUTCDate()).slice(-2))+"-"+dt.getUTCFullYear();
console.log(ddte);
Though in this case I see no use for using Date at all; this should suffice:
var parsedDate = "2016-06-21".replace(/(\d{4})-(\d{2})-(\d{2})/, "$2-$3-$1");
console.log(parsedDate);
It isn't a bug. It's just how time zones work (it isn't the same calendar day everywhere in the world at the same time).
If you don't actually want advanced date features (it seems you only want some good old string manipulation) my tip is to just not use Date in the first place.
var parts = "2016-06-21".split("-");
var mdy = parts[1] + "-" + parts[2] + "-" + parts[0];
Add some error checking and you're done.

Get MongoDB items matching date

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*/})

How to Convert date string to json date format in javascript?

In my application I am getting date in a string format like :
var date="1988-11-4".
I am calling back the WCF service and sending data to the service as Json format. But my problem is the WCF service is only accepting the dates as {DoB:"/Date(570931200000+0530)/"} format.
can you please tell how do I convert date to json date format like:
var jasonDate="/Date(570931200000+0530)/". Where 570931200000 is the miliseconds calculated since from "1970-01-01" and +0530 is the Timezone.
As a best guess, and to give you something to work with, until you understand what the relationship is and come back and explain things better along with what you have tried and the precise nature of the problem with your code.
var dateTime = '1988-05-03',
parts = dateTime.split('-'),
date;
parts[1] -= 1;
date = new Date(Date.UTC.apply(null, parts));
document.body.textContent = '/Date(' + date.getTime() + '-0000)/';
This might work:
var jsonDate = new Date(date).toJSON();
As the initial variable is only a string it would not be recognised as a date so create a date from it then convert that to JSON.
Thank you all for your response. I have got solution to my query. Here in the string "/Date(1208559600000-0700)/" 1208559600000 is the milliseconds calculated since from Jan 01 1970 and -700 is the time zone.
This the code that worked for me:
convertToJsonDate: function (date) {
var diff = date.getTime();
var jsonDate = "\/Date(" + diff + "-0700)\/";
return jsonDate;
},

JavaScript/jQuery datetime difference

I am trying to identify whether given date-time is future date and time or not.
For e.g. My current date time is '25-04-2010 08:26 PM' and if I pass '25-04-2010 09:00 PM' to a JavaScript function, then it should return me '1' if that date-time is future date & time otherwise it should return me '0'.
I decided to do this using timestamp. So I just wrote below code.
var myDate = new Date("April 25, 2011 21:16:00"); // Your timezone!
var myEpoch = myDate.getTime()/1000.0;
document.write(myEpoch);
var cur_date = new Date(); // Current date
var myEpoch1 = cur_date.getTime()/1000.0;
document.write("---"+myEpoch1);
var diff=myEpoch-myEpoch1; // If diff comes minus value, then it is past date-time, otherwise it is future data-time
alert(diff);
thanks.
var myDate=new Date();
myDate.setFullYear(2010,0,14);
var today = new Date();
if (myDate>today)
{
alert("Today is before 14th January 2010");
}
else
{
alert("Today is after 14th January 2010");
}
source: link
This seems like a simple parsing job to me. I won't give you the code, but will give you the approach.
Use split to split the string on ' ' (empty space)
Use split to split the first string [0] on '-'
Use split to split the second string [1] on ':'
-- Now simply concatenate all the strings in the order yyyymmddhhmmss
so your time string will become a signature like : 201004250900
and the second one becomes : 201003250826
Now simply do an integer compare ;)
This is the long winded approach
It just occurred to me that you should be able to parse the time string you're passing to date in javascript, and that makes your life easier... Try that.

Categories