converting epoch into month - javascript

I wanted to convert the epoch '1326067200000' into month, i.e., 'January'.
var d = new Date(1326067200000).format("%B");
print (d);
Not working though.
What's the easiest and elegant way of doing it?

See toLocaleDateString():
var month = new Date(1326067200000).toLocaleDateString('en-US', {month: 'short'})
At the time of writing, you'll have to patch Safari: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#Browser_compatibility
Alternatively, you can get a 0-numbered month with getMonth():
var monthNames = ['Jan','Feb','Mar']
var month = monthNames[new Date(1326067200000).getMonth()];

Related

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>

Formatting dates when getting days between 2 dates with JQuery/Javascript

I am trying to calculate the days between 2 dates and it is working as far as I can tell but I keep getting stupidly high numbers which clearly isn't right, I have a feeling this is the way my dates are set out. my dates are set out as dd/mm/yyyy and this is the code I am using:
var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);
This is the question I used to get the answer:
JavaScript date difference Days
When it writes to the console this is the result I get:
diff=>17301.95833332176
I have had a play with the code, although I have not used HTML, i set the vars statically below.
var end_date = new Date("May 25, 2017");
var start_date = new Date("May 23, 2017");
var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);
I have also checked it with a 3 value date format
var end_date = new Date(2017,4,25);
var start_date = new Date(2017,4,23);
var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);
I manage to get an output of 2. Which is what i expected. The code you supplied looks ok to me. Maybe look at the HTML to check that the values being passed are in the correct format.
Jquery datepicker may be of help to you here.
You could also use moment: https://momentjs.com
var moment = require('moment');
var start_moment = moment(start_date);
var end_moment = moment(end_date);
var days = start_moment.diff(end_moment, 'days');
console.log("diff=>" + days);
You can also get weeks, months etc. with this method
Easy solution, is to use countBtw
var { date } = require('aleppo')
//..
date.countBtw('all', date1, date2)

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.

Extract Month and Day in 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.

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