combine date and time into a single datetime [duplicate] - javascript

This question already has answers here:
Combine date and time string into single date with javascript
(8 answers)
Closed 3 years ago.
I have a date and time control, which I would like to concatenate
var startDate = jQuery('#startDatepicker').find("input").val();
var startTime = jQuery('#startTimepicker').find("input").val();
I have another var field which has data as below:
var targetTime = new Date().setMinutes(-5).valueOf();
startDatepicker has the value as : 02/06/2017
startTimepicker, currentTime has the value as : 05:17 am
targetTime has the value as: 1486374940591
I want to concatenate startdate and starttime in the format of targetTime. How to concatenate the start date and start time?
Thanks

This do what you need
var date = new Date(startDate + ' ' + startTime);
jQuery('#startDatepicker, #startTimepicker').on('input', function() {
var startDate = jQuery('#startDatepicker').val();
var startTime = jQuery('#startTimepicker').val();
var date = new Date(startDate + ' ' + startTime);
console.log(date)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Date
<input id="startDatepicker">Time
<input id="startTimepicker">

Pass your date and time to this function. It will return the Date object. Use getTime() on that to get the desired result. Codepen example.
function getAsDate(day, time)
{
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "pm" && hours<12) hours = hours+12;
if(AMPM == "am" && hours==12) hours = hours-12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10) sHours = "0" + sHours;
if(minutes<10) sMinutes = "0" + sMinutes;
time = sHours + ":" + sMinutes + ":00";
var d = new Date(day);
var n = d.toISOString().substring(0,10);
var newDate = new Date(n+"T"+time);
return newDate;
}

Related

Current Date converted to 10 days before and 10 days after

I have this code where I convert the current date to this format 2020-08-20 . But how do I alter it to give me the date 10 days from today and 10 days before today.
eg today is 2020-08-20 I am trying to get 10 days from today 2020-08-30
This is my code
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
console.log(dateConverter(today));
It's a little bit tricky. First set the hours from the date to 12 for avoiding problems with summer/wintertime-changing. Then use getDate add 10 for the extra days and setDate with the new value. Now you have a value in milliseconds, generate out of this a new date to get an dateobject. For the second date subtract 20 days because the original date was changed by the action before and do all other the same.
Format the output for the dates with getFullYear, getMonth and getDate
. Because month is handled in JS from 0 to 11 add 1 month. Months and days could be 1-digit but you want it 2 digits, so add before the string "0" and get the last 2 chars of it with slice.
Do the format for both dates and return them as array.
const dateConverter = (dateIn) => {
dateIn.setHours(12);
let dateIn10days = new Date(dateIn.setDate(dateIn.getDate() + 10));
let dateFor10days = new Date(dateIn.setDate(dateIn.getDate() - 20));
let strIn10Days = dateIn10days.getFullYear() + '-' + ('0' +(dateIn10days.getMonth()+1)).slice(-2) + '-' + ('0' + dateIn10days.getDate()).slice(-2);
let strFor10Days = dateFor10days.getFullYear() + '-' + ('0' +(dateFor10days.getMonth()+1)).slice(-2) + '-' + ('0' + dateFor10days.getDate()).slice(-2);
return [strFor10Days, strIn10Days];
}
let today = new Date();
console.log(dateConverter(today));
Try this
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
var numberOfDaysToAdd = 10;
var tenDaysPlus = today.setDate(today.getDate() + numberOfDaysToAdd);
console.log(dateConverter(today));
var today = new Date();
var numberOfDaysToSubtract = 10;
var tenDaysMinus = today.setDate(today.getDate() - numberOfDaysToSubtract);
console.log(dateConverter(today));
I would suggest you to use the moment library but you still want plain javascript
const convert = (date) => {
const pastDate = new Date(date)
pastDate.setDate(pastDate.getDate() - 10);
const futureDate = new Date(date)
futureDate.setDate(futureDate.getDate() + 10);
return { pastDate, futureDate }
}
call convert function with any date.
This code will help you
Reference JavaScript calculating date from today date to 7 days before
for after 10 days just just convert the - to +
const dateConverter = (dateIn) => {
var dates ={};
var days = 10; // Days you want to subtract
for(let i=0;i<days;i++){
var date = dateIn;
var last = new Date(date.getTime() - (i * 24 * 60 * 60 * 1000));
var day = last.getDate();
var month= last.getMonth()+1;
var year= last.getFullYear();
dates[i] = year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
return dates
}
var today = new Date();
console.log(dateConverter(today));
I've been messing around that before as well.
But on this Stack Overflow you can find a really good answer:
Add days to JavaScript Date
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
alert(date.addDays(5));
This is the code taken from that post.
For subtracting days, just replace the "+ days" with "- days"
Hope this solved your problem!
You can convert all the dates to timestamp and then simply calculate with them:
const dateTimestamp = new Date("2020-10-10").getTime()
const milisecondsInADay = 60*60*24*1000
const milisecondsInTenDays = milisecondsInADay * 10
const beforeDate = new Date(dateTimestamp - milisecondsInTenDays)
const afterDate = new Date(dateTimestamp + milisecondsInTenDays)
console.log("before", beforeDate)
console.log("after", afterDate)
console.log("initially", new Date(dateTimestamp))

javascript date format yyyy-mm-dd HH:MM:ss [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 2 years ago.
I have facing an issue in javascript date format all dates in this format yyyy-mm-dd HH:MM:ss
My Code:
var currentdate = new Date();
var prevdate = new Date();
var firstdate = new Date();
prevdate.setTime(currentdate.getTime() - (30 * 60 * 1000));
firstdate.setTime(currentdate.getTime() + (30 * 60 * 1000));
var current = currentdate.toLocaleTimeString();
var previous = prevdate.toLocaleTimeString();
var first = firstdate.toLocaleTimeString();
console data
console.log(previous); //10:28:24 PM
console.log(current); //10:58:24 PM
console.log(first); //11:28:24 PM
I try this , how can i pass previous and first date
var Currentdate=dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
console.log("Currentdate"); //2020-05-07 22:58:11
Expected Output Date Format: yyyy-mm-dd HH:MM:ss
previous date: 2020-05-07 22:28:11 // date before 30min
current date: 2020-05-07 22:58:11 // current date
first date: 2020-05-07 23:28:11 // date after 30min
What should i do? can anyone help?
You should use currentdate.toLocaleString() instead, as toLocaleTimeString()
returns a string with a language sensitive representation of the time portion of this date
toLocaleString
toLocaleTimeString
Use toLocaleString instead of toLocaleTimeString
Hi please try th following function:
function getTime(){
var date = new Date();
console.log(GetFormattedDate(date));
}
function GetFormattedDate(date) {
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + (date.getDate())).slice(-2);
var year = date.getFullYear();
var hour = ("0" + (date.getHours())).slice(-2);
var min = ("0" + (date.getMinutes())).slice(-2);
var seg = ("0" + (date.getSeconds())).slice(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg;
}
in your case
function getTime(){
var date = new Date();
var currentdate = new Date();
var prevdate = new Date();
var firstdate = new Date();
prevdate.setTime(currentdate.getTime() - (30 * 60 * 1000));
firstdate.setTime(currentdate.getTime() + (30 * 60 * 1000));
console.log(GetFormattedDate(prevdate));
console.log(GetFormattedDate(currentdate));
console.log(GetFormattedDate(firstdate));
}
function GetFormattedDate(date) {
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + (date.getDate())).slice(-2);
var year = date.getFullYear();
var hour = ("0" + (date.getHours())).slice(-2);
var min = ("0" + (date.getMinutes())).slice(-2);
var seg = ("0" + (date.getSeconds())).slice(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg;
}
regards
You need to use toLocaleString
var currentdate = new Date();
var prevdate = new Date();
var firstdate = new Date();
prevdate.setTime(currentdate.getTime() - (30 * 60 * 1000));
firstdate.setTime(currentdate.getTime() + (30 * 60 * 1000));
var options = { hour12: false };
var current = currentdate.toLocaleString('en-US', options);
var previous = prevdate.toLocaleString('en-US', options);
var first = firstdate.toLocaleString('en-US', options);
current = current.replace(/\//g, '-');
previous = previous.replace(/\//g, '-');
first = first.replace(/\//g, '-');
console.log(`current: ${current}`);
console.log(`previous: ${previous}`);
console.log(`first: ${first}`);

Convert timestamp to yyyy-mm-dd hh:mm:ss format using javascript [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript? [duplicate]
(4 answers)
Closed 3 years ago.
I need to convert the current timestamp (Eg: 1578293326452) to yyyy-mm-dd hh:mm:ss format
using javascript.
I obtained the current timestamp as follows:
var date = new Date();
var timestamp = date.getTime();
How can I change the format?
function getTime(){
var date = new Date();
var year = date.getFullYear();
var month = (date.getMonth() +1);
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
return formateTime(year, month, day, hour, minute, second);
}
function formateTime(year, month, day, hour, minute, second){
return makeDoubleDigit(year) + "-" +
makeDoubleDigit(month) + "-" +
makeDoubleDigit(day) + " " +
makeDoubleDigit(hour) + ":" +
makeDoubleDigit(minute) + ":" +
makeDoubleDigit(second);
}
function makeDoubleDigit(x){
return (x < 10) ? "0" + x : x;
}
console.log(getTime())
Maybe this is what you need
d = Date.now();
d = new Date(d);
d = (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+' '+(d.getHours() > 12 ? d.getHours() - 12 : d.getHours())+':'+d.getMinutes()+' '+(d.getHours() >= 12 ? "PM" : "AM");
console.log(d);

Adding a week to date javascript

I have a JSfiddle which I am trying to add a week onto a date. The date is outputting incorrect date when I try to add six days.
fiddle
code for adding a week
var endDate = new Date(date || Date.now()),
eMonth = '' + (monthNames[endDate.getMonth()]),
eDay = '' + (endDate.setDate(endDate.getDate() + 6)),
eYear = endDate.getFullYear();
Try this,
var endDate = new Date(date || Date.now());
var days = 6;
endDate.setDate(endDate.getDate() + days);
var eMonth = '' + (monthNames[endDate.getMonth()]),
eDay = '' + endDate.getDate(),
eYear = endDate.getFullYear();
Working Demo
Give this a try,
var endDate = new Date(date || Date.now());
endDate.setTime(startDateObj.getTime() + (1000 * 60 * 60 * 24 * 7));
var newDate = endDate.getFullYear()+"-"+(endDate.getMonth() + 1)+"-"+endDate.getDate();
eDay = '' + (endDate.getDate() + 6)
Remove setDate() function and change $("#startDate").text(startDate) to show value in span tag
var now = new Date().getTime();
var oneWeek = 6*24*60*60*1000;
var newDate = now+oneWeek;
alert(new Date(newDate));
this should do the work
You can also use the get/set Time methods:
var today = new Date();
var plusOneWeek = new Date();
plusOneWeek.setTime( today.getTime()+(7*24*3600*1000) ); //add 7 days
See the doc about getTime() on MDN

Set new date 12 months after in a form

I am very new to script and checked many answers but could not find the complete answer.
In a form, I have a start date, number of months and end date - I want to display the end date when the start date is entered - I have created this script but I must be missing something.
Here's my code:
[script type="text/javascript" src=Datejs][/js]
[script type="text/javascript" ]
window.onload = function() {
var startdateEl = document.getElementById("customFields_cf_232");
var leasetermEl = document.getElementById("customFields_cf_34");
var enddateEl = document.getElementById("customFields_cf_38");
function CalculateDate {
var enddateEl=leasetermEl.months().startdateEl;
}
var enddateEl.onblur = CalculateDate;
};
[/script]
I made this. It listens to your keystrokes live. http://jsfiddle.net/4t54J/
<input name="startDate" type="text" value="MM-DD-YYYY" />
<input name="endDate" type="text" />
var SECOND = 1000;
var MINUTE = SECOND * 60;
var HOUR = MINUTE * 60;
var DAY = HOUR * 24;
var YEAR = DAY * 365.25;
var startDateInput = 'input[name="startDate"]';
var endDateInput = 'input[name="endDate"]';
$(startDateInput).live('keypress', function (e) {
var startDate = $(startDateInput).val();
var endDate = setEndDate(startDate);
$(endDateInput).val(endDate);
});
function setEndDate(startDate) {
var date = new Date();
var parts = startDate.split('-');
if (date != '' && parts.length > 2) {
// year, month (0-based), day
date.setFullYear(parts[2], parts[0] - 1, parts[1]);
date.setTime(date.getTime() + YEAR);
var mm = date.getMonth() + 1;
mm = (mm < 10 ? '0' : '') + mm.toString();
var dd = date.getDate();
var yyyy = date.getFullYear();
return mm + "-" + dd + "-" + yyyy;
} else {
return '';
}
}

Categories

Resources