Extract Month and Day in Javascript - javascript

I have the date in this format: 1347564203.713372
And need to end up with 2 variables, one that is the month from that date and another that is the day from that date.
How do I do this using Javascript/jQuery?

This should do:
var myDate = 1347564203.713372;
var d= new Date(myDate*1000);
var month = d.getMonth();
var day = d.getDate();

Create a Date object, use setTime to put your timestamp in there, then get the relevant parts:
var d = new Date(), t = 1347564203.713372;
d.setTime(t*1000); // JS uses timestamps in milliseconds
alert(d.getUTCDate());
alert(["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][d.getUTCMonth()]);
Note use of getUTC* functions - this helps avoid timezone issues and DST.

Related

I need to get all the dates between any two dates in JavaScript

Using this code I am getting the dates excluding the start dates
var startdate = new Date("");
var enddate = new Date("");
while (startdate < enddate) {
startdate.setDate(startdate.getDate() + 1);
dates.push(new Date(startdate).format("mm/dd/yyyy"));
}
You should replace new Date(startdate) with new Date(startdate.getTime()) to avoid JS error. However, you cannot simply format JS Date object with format(), as this function does not exist, you have to extract year, month, day by yourself. If you want to do it, beware the month value is started from zero.
Please consider using a library like Moment.js instead, it is a lot handy to manipulate date, time and duration.
You can't simply format javascript date using format function, which doesn't exists. You need to split date, month, year and join. Here it may help-
var startdate = new Date();
var enddate = new Date("2019, 10, 23");
while (startdate < enddate) {
startdate.setDate(startdate.getDate() + 1);
dates.push(startdate.getMonth()+1+"/"+startdate.getDate()+"/"+startdate.getFullYear());
}
You have to increase moth by 1 startdate.getMonth()+1 because month starts from 0 in JS.
Consider using Moment.js which has lots of facility.

Moment js Time Ago calculate wrong date

maybe a simple question but i don't get it.
var date = new Date();
test = date.toISOString();
alert(moment(test, "YYYYMMDD").fromNow());
Will return "16 hours", but why?
Demo: https://jsfiddle.net/5jacaxbf/
Because you are using moment(String, String), instead of moment(String) (toISOString() output is obviously in ISO 8601 format) or moment(Date).
So moment(test, "YYYYMMDD") will be the start of the day instead of the current time.
As the Default section states:
You can create a moment object specifying only some of the units, and the rest will be defaulted to the current day, month or year, or 0 for hours, minutes, seconds and milliseconds.
var date = new Date();
test = date.toISOString();
var m1 = moment(test, "YYYYMMDD")
console.log(m1.format());
console.log(m1.fromNow());
var m2 = moment(test)
console.log(m2.format());
console.log(m2.fromNow());
var m3 = moment(date)
console.log(m3.format());
console.log(m3.fromNow());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Convert nonstandard date with short month to timestamp

I have unfortunetly a nonstandard date
Jul-23-2017
Is there any way to convert it to a unix timestamp in javascript?
new Date("Jul-23-2017").getTime();
To make sure you pass valid values to the date contructor, you can parse the date yourself
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var date = "Jul-23-2017";
var parts = date.split('-');
var unix = (new Date(parts[2], months.indexOf(parts[0]), parts[1])).getTime();
console.log(unix)

What is the proper way to create a timestamp in javascript with date string?

I have date format returned as 05-Jan, 12-feb etc.. when i convert current date using date object in javascript . I did something like this
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDay(),
today = new Date(curr_year, curr_month, curr_day, 0, 0, 0, 0);
console.log(today);
Here the today is returned as invalid date i needed the create a timestamp which should not include minutes secs and millisecs as zero for date comparison of month and date alone based on that i can categories .Is there way to dynamically create a date and compare those dates for given format.
And when i try to convert my date string using date object it returns year as 2001. how can i compare dates based upon current year.
For eg: in php i have used mktime to create a date dynamically from given date format and compare those results. Any suggestion would be helpful. Thanks.
You can leverage the native JS Date functionality to get human-readable date strings for time stamps.
var today = new Date();
console.log( today.toDateString() ); // Outputs "Mon Feb 04 2013"
Date comparison is also built in.
var yesterday = new Date();
yesterday.setDate( yesterday.getDate() - 1);
console.log( yesterday.toDateString() ); // Outputs "Sun Feb 03 2013"
console.log( yesterday < today ); //Outputs true
You can use the other built-in methods to fine-tune this comparison to be/not be sensitive to minutes/seconds, or to set all those to 0.
You said that you used mktime() in php, so what about this?
change to this :
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth()+1,
curr_day = curr.getDay(),
today = curr_month+'/'+curr_day+'/'+curr_year;
console.log(today);
(getMonth()+1 is because January is 0)
change the :
today = curr_month+'/'+curr_day+'/'+curr_year;
to whatever format you like.
I have found a way to convert the date into timestamp i have tried as #nbrooks implemented but .toDateString has built in date comparison which works for operator < and > but not for == operator to do that i have used Date.parse(); function to achieve it. Here it goes..
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDate(),
today = new Date(curr_year, curr_month, curr_day, 0,0,0,0);
var dob = new Date('dob with month and date only'+curr_year);
if(Date.parse(dob) == Date.parse(today)){
//Birthdays....
}
This method can be used to create a timestamp for dynamically created date.Thanks for your suggestions.

convert iso date to milliseconds in javascript

Can I convert iso date to milliseconds?
for example I want to convert this iso
2012-02-10T13:19:11+0000
to milliseconds.
Because I want to compare current date from the created date. And created date is an iso date.
Try this
var date = new Date("11/21/1987 16:00:00"); // some mock date
var milliseconds = date.getTime();
// This will return you the number of milliseconds
// elapsed from January 1, 1970
// if your date is less than that date, the value will be negative
console.log(milliseconds);
EDIT
You've provided an ISO date. It is also accepted by the constructor of the Date object
var myDate = new Date("2012-02-10T13:19:11+0000");
var result = myDate.getTime();
console.log(result);
Edit
The best I've found is to get rid of the offset manually.
var myDate = new Date("2012-02-10T13:19:11+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(withOffset);
console.log(withoutOffset);
Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.
EDIT
Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.
A shorthand of the previous solutions is
var myDate = +new Date("2012-02-10T13:19:11+0000");
It does an on the fly type conversion and directly outputs date in millisecond format.
Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.
var myDate = Date.parse("2012-02-10T13:19:11+0000");
Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.
var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);
See the fiddle for more details.
Yes, you can do this in a single line
let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673
Another possible solution is to compare current date with January 1, 1970, you can get January 1, 1970 by new Date(0);
var date = new Date();
var myDate= date - new Date(0);
Another solution could be to use Number object parser like this:
let result = Number(new Date("2012-02-10T13:19:11+0000"));
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();
console.log(result);
console.log(resultWithGetTime);
This converts to milliseconds just like getTime() on Date object
var date = new Date()
console.log(" Date in MS last three digit = "+ date.getMilliseconds())
console.log(" MS = "+ Date.now())
Using this we can get date in milliseconds
var date = new Date(date_string);
var milliseconds = date.getTime();
This worked for me!
if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);
In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.
let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The output will be the only the time from isoDate which is,
15:27

Categories

Resources