Javascript Concatenate dates and time together - javascript

I have this code which generates the current date + time in javascript:
var date_variable = new Date();
var year = date_variable.getFullYear();
var month = date_variable.getMonth() + 1;
var day = date_variable.getDate();
var hour = date_variable.getHours();
var minutes = date_variable.getMinutes();
var seconds = date_variable.getSeconds();
var full_date = year + month + day + hour + minutes + seconds;
console.log(year);
console.log(month);
console.log(day);
console.log(hour);
console.log(minutes);
console.log(seconds);
console.log(full_date);
Everything in console displays fine, except when it comes to the full_date variable. This is what's displayed in console:
2014
8
27
10
53
10
2122
My question is, why does the last output not combine my date + time into a single string?
Thanks

You need to concatenate the numbers with a string first.
var full_date = year +""+ month +""+ day +""+ hour +""+ minutes +""+ seconds;

Each of the properties you are accessing return a number. When you add them together with the + operator, you are just adding numbers together.
If you substitute the variables used in full date, it would look something like:
var full_date = 2014 + 8 + 26 + . . .
All you have to do is put a strings in the expression and you will get what you want.
In all honesty though, you should use Date.toLocalDateString() or Date.toLocalTimeString() if the format works for you. You can read the documentation about them on MDN's Date reference page.

Related

Formatting seconds duration into DD:HH:mm format by using moment.js

I'm trying to count calculate a duration from seconds into a DD-HH-mm format.
My javascript code:
var seconds = 120;
var result = moment.utc(seconds*1000).format('DD:HH:mm');
My code should return something like this: 00:00:02 (DD:HH:MM) but it returns that: 01:00:02 (DD:HH:MM)!
I'm sure that's because of my local time, but how to fix the 1 hour interval in general?
moment.utc creates a moment.js object with a timezone set to GMT/UTC. When using a date for a duration, you need to allow for the date starting from 1, not zero. Also, if the duration is 32 days or longer, the "days" will reset to 1.
Moment.js also has durations, however, they don't support formatting other than "humanize" or converting to particular units.
If your durations are less than 32 days, you can use a date starting from 1 January in any year provided you deal with the day number not being zero indexed (i.e. subtract 1 from the day).
So getting your required format with moment.js is a bit more work than just formatting a date, you'll need a sequence of steps so consider writing a function. A plain JS function is no more work than a moment one in this case, it will handle durations 32 days or longer and is not affected by Date vagaries like daylight saving and timezones.
var secs = 120;
// Using a duration
var m = moment.duration(secs * 1000);
console.log(m);
console.log(m.humanize());
console.log(m.asMinutes());
// Using a date and seconds value
var x = moment.utc(secs*1000);
// Generated date
console.log(x.format());
// Get the days separately
var dayNum = x.format('D') - 1;
// Format with hours and minutes
console.log(('0'+dayNum).slice(-2) + x.format(':HH:mm'))
// Function using moment.js
function myFormat(secs) {
var x = moment.utc(secs*1000);
var dayNum = x.format('D') - 1;
return ('0'+dayNum).slice(-2) + x.format(':HH:mm');
}
// Function without using a Date
function duration(secs) {
function z(n){return ('0'+n).slice(-2)}
return z((secs/8.64e4|0))
+ ':' + z((secs%8.64e4)/3.6e3|0)
+ ':' + z((secs%3.6e3)/60|0)
// + ':' + z(secs%60);
}
console.log(duration(secs));
// Some other tests
var min = 60;
var hr = 60*min; // 3,600
var day = 24*hr; // 86,400
//2 days 17 hours 53 minutes and 08 seconds
var d = 2*day + 17*hr + 53*min + 8;
//0 days 1 hour 2 minutes and 1 second
var e = 0*day + 1*hr + 2*min + 1;
// 48 days 21 hours 15 minutes
var f = 48*day + 21*hr + 15*min;
[120, d, e, f].forEach(function(d) {
console.log(d + ' seconds');
console.log('Plain js: ' + duration(d));
console.log('Moment fn: ' + myFormat(d));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
The format seems ambiguous, I think many would interpret it as HH:mm:ss rather than DD:HH:mm.

displaying the day of the week 3 days before today's date using javascript

I tried this javascript to display the day of the week from 3 days before the html page is accessed. It doesn't work when today is Sunday, Monday or Tuesday.
(I think the problem is that the days are numbered 0-6 with no consideration of negative numbers in the line var date)
var now = new Date();
var days = new Array(
'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
var months = new Array(
'January','February','March','April','May',
'June','July','August','September','October',
'November','December');
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate()-3;
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;}
today = days[now.getDay() -3] + ", " +
months[now.getMonth()] + " " +
date + ", " +
(fourdigits(now.getYear()));
document.write(today);
There are a number of issues with your code.
<SCRIPT LANGUAGE="JavaScript">
The language attribute for script elements was deprecated in HTML 4 and removed in subsequent versions.
<!--
HTML comment delimiters are tolerated at the start and end of script elements but should not be used. They have been unnecessary for 20 years.
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate()-3;
When the date is 1 to 3, the first part of the expression will return a string like "0" or "". The second part will return a number from -2 to 0, so the result will be "0-2" to "00".
You can do something like:
var date = now.getDate();
date = (date < 10? '0' : '') + date;
Then there is:
today = days[now.getDay() -3] + ", " +
getDay returns a number representing the day of the week, 0 for Sunday to 6 for Saturday, so from Sunday to Tuesday (day numbers 0–2) you'll be attempting to access a property of days that doesn't exist, which will return undefined.
(fourdigits(now.getYear()));
getYear always returns the year less 1900. Use getFullYear instead.
See Where can I find documentation on formatting a date in JavaScript? and Add +1 to current date.
You should start by subtracting 3 days from the date, then format the result for output:
var now = new Date();
now.setDate(now.getDate() - 3);
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday', 'Friday','Saturday'];
var months = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
var date = now.getDate();
date = (date < 10? "0" : "") + date;
var today = days[now.getDay()] + ", " +
months[now.getMonth()] + " " +
date + ", " + now.getFullYear();
document.write(today);

Convert EDT timestamp to PST with regex / JavaScript

A third party is providing me with an EDT time-stamp in the following format:
MM/DD/YYYY hh:mm
for instance: '08/19/2013 11:31'
I need to convert it to PST with JavaScript (same date time format) and have been looking all over but can't find any info about doing this.. If someone can help me with some example code I would really appreciate it.
If you wanted to do this manually, you can try the following:
Split by a space, so you have date and time.
Split the time by ":" and split the date by "/".
Create a new Date() and provide the right values in the right order.
Subtract 3 hours using the proper methods, then recreate the format.
Here's an example of all this:
var est = "01/01/2014 02:31",
finalDate, pst;
finalDate = parseDateString(est);
finalDate.setHours(finalDate.getHours() - 3);
pst = formatDate(finalDate);
console.log(pst);
function parseDateString(str) {
var dateTime, date, time, dateSplit, month, day, year, timeSplit, hour, minute;
dateTime = est.split(" ");
date = dateTime[0];
time = dateTime[1];
dateSplit = date.split("/");
month = dateSplit[0] - 1;
day = dateSplit[1];
year = dateSplit[2];
timeSplit = time.split(":");
hour = timeSplit[0];
minute = timeSplit[1];
return new Date(year, month, day, hour, minute);
}
function formatDate(d) {
return padZero(d.getMonth() + 1) + "/" + padZero(d.getDate()) + "/" + d.getFullYear() + " " + padZero(d.getHours()) + ":" + padZero(d.getMinutes());
}
function padZero(num) {
if (+num < 10) {
num = "0" + num;
}
return "" + num;
}
DEMO: http://jsfiddle.net/MmVmR/
The padZero function is there just to prepend any 0s in case the number is less than 10.
Reference:
Dates in JS - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Javascript UNIX time conversion

Hi I have the following problem I am converting this UNIX timestamp to javascript string for date: here is the jsfiddle for it http://jsfiddle.net/tczeU/ and as everyone can see the date is 2 6 2013 13:15:44 so the problem is that this number 1373969744 in UNIX timestamp converter is Tue, 16 Jul 2013 10:15:44 GMT The problem are that there are 14 days bwtween the two dates where does I go wrong? Please help me to convert this date. The code is as in the fiddle:
var date = new Date(1373969744*1000);
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var year = date.getFullYear();
var day = date.getDay();
var month = date.getMonth();
var string =day + " " + month + " " + year + " " + hours + ':' + minutes + ':' + seconds;
$("#view").html(string);
and the html:
<div id="view"></div>
So no errors there. Please help. Any help will be apreciated!
You are using the wrong function to get the day of the month. You are using the function that returns the day of the week, hence the 2 since it's a Tuesday. Check out http://www.w3schools.com/jsref/jsref_obj_date.asp
You need to change .getDay to .getDate and it will work just fine. Or at least it did for me using your jsFiddle link.
Also, don't forget to add one to your month so it has Jul as 7th month instead of 6th like you have it now.

Calculate the Date based on Current Date and No of Days using Javascript/Jquery

I need a help..
I have a Current Date and No of days column.
When i enter number of days,i should add current date plus no of days entered.
For example,
todays date 5th jan + 20(no of days) = 25th Jan 2011 in another column.
Kindly help me.
Thanks in Advance.
Date.js is fantastic for this.
Date.today().add(5).days();
As you are learning JavaScript you may find the w3schools site useful for simple examples of objects and functions that are exposed and how they may be used.
http://www.w3schools.com/jsref/jsref_obj_date.asp
You can calculate the date as follows:
var d = new Date(); // Gets current date
var day = 86400000; // # milliseconds in a day
var numberOfDays = 20;
d.setTime(d.getTime() + (day*numberOfDays)); // Add the number of days in milliseconds
You can then use one of the various methods of displaying the date:
alert(d.toUTCString());
You could do something like
Date.today().add(X).days();
Where X is the number of days the user has entered.
You can add dates like this in js:
var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
var month = someDate.getMonth() + 1; //Add 1 because January is set to 0 and Dec is 11
var day = someDate.getDate();
var year = someDate.getFullYear();
document.write(month + "/" + day + "/" + year);
See this p.cambell's answer here: How to add number of days to today's date?

Categories

Resources