UTC timestamp conversion to selected timezone timestamp - javascript

this.selectedTimezone="Pacific/Kiritimati";
//this value will come from dropdown
this.records = data.body; //api response
for (var i = 0; i < this.records.length; i++)
{
var d = new Date(this.records[i]['startTimeStamp']);
//it is converting to system timezone date format. I want this one to selected timezone conversion.
var t1 = moment(d).tz(this.selectedTimezone).format();
//2018-11-23T05:30:00+14:00
}
I want this t1 in full date format i.e Friday November 30, 2018 09:00:00

See Moment and Moment-timezone.
// This will get "Pacific/Kiritimati" current timezone.
var datetime = moment().tz("Pacific/Kiritimati").format();
var timestamp = moment().tz("Pacific/Kiritimati").valueOf();
console.log(datetime);
console.log(timestamp);
<script src="https://rawgit.com/moment/moment/2.22.2/min/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.js"></script>

var d1= moment.tz(new Date(this.records[i]['startTimeStamp']), this.selectedTimezone);
var key = d1.year() + "-" + ('0' + (d1.month() + 1)).slice(-2) + "-" + ('0' + (d1.date())).slice(-2);
var timeSlot = ('0' + d1.hour()).slice(-2) + ":" + ('0' + d1.minutes()).slice(-2);
example:-
var d1= moment.tz(new Date(2543622499000), "Pacific/Kiritimati");
var key = d1.year() + "-" + ('0' + (d1.month() + 1)).slice(-2) + "-" + ('0' + (d1.date())).slice(-2);
var timeSlot = ('0' + d1.hour()).slice(-2) + ":" + ('0' + d1.minutes()).slice(-2);
output:-2050-08-09 15:48

Related

How to get the date one month before from current date, when current date is January?

I used a plugin called jQRnageSlider and tried to get the date and time label showed in the slider, but when I scroll back the slider to last year, the month 12 turns out to be 11 eventually.
Normal case if I don't scroll back to last year.
It jumped to Nov 2016 immediately
That should be the issue of date formatting issue. Can anyone help?
$(".date-range-slider").dateRangeSlider({
...
formatter: function(val){
var days = ('0' + val.getDate()).slice(-2),
month = ('0' + val.getMonth() + 1).slice(-2),
year = val.getFullYear(),
hour = ('0' + val.getHours()).slice(-2),
min = ('0' + val.getMinutes()).slice(-2);
return days + "-" + month + "-" + year + " " + hour + ":" + min;
}
});
The problem is that line:
month = ('0' + val.getMonth() + 1).slice(-2)
You want to sum it mathematically not as string, so you should do:
month = ('0' + (val.getMonth() + 1)).slice(-2)
Check the snippet to see what your code is actually returning:
var val = new Date();
document.write('0' + val.getMonth() + 1)
And what returns corrected version:
var val = new Date();
document.write('0' + (val.getMonth() + 1))

how to change the date format using jquery

I have a input date field whose value is in this "2014-06-07 07:14"(year-month-date hour:minute) format how can i change it to 06/07/2014 07/14( mm/dd/yy) format using jquery.
DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("dd/MM/yyyt hh/mm");
Date date = originalFormat.parse("2014-06-07 07:14");
String formattedDate = targetFormat.format(date); // 06/07/2014 07/14
Docs of SimpleDateFormat#format
PS: A JavaScript implementation of the format() method of Java's SimpleDateFormat: is available here
Why using jQuery to do this ?
Use plain js:
var date = new Date('2014-06-07 07:14');
alert((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear() + ' ' + date.getHours() + '/' + date.getMinutes());
http://jsfiddle.net/F4nq8/
It seems that IE and Safari have some bug with YYYYMMDD dates so a workaround could be something like:
var s = "2014-06-07 07:14";
var t = s.split(" ");
var d = t[0].split("-");
var x = d[1] + "/" + d[2] + "/" + d[0] + " " + t[1];
var date = new Date(x);
alert((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear() + ' ' + date.getHours() + '/' + date.getMinutes());
http://jsfiddle.net/F4nq8/4/
Some reference about this behaviour: http://biostall.com/javascript-new-date-returning-nan-in-ie-or-invalid-date-in-safari

How to parse Date from JSON

I am using a grid view which is getting bind by json also on some conditions and a coloum of grid contains date , so while getting data from json, I need to parse the date. I am able to get date but not time part . Tried and searched too much . I am mentioning below two methods that I tried but not solves my problem.
{
function ParseDate(jsonDate) {
date = new Date(parseInt(String(jsonDate).substr(6)));
day = date.getDate();
month = date.getMonth() + 1;
year = date.getFullYear();
return month + "/" + day + "/" + year;
}
}
This gives me only date but I need time, so I did one more method
{
function ParseDate(jsonDate) {
var date = new Date(parseInt(jsonDate.substr(6)));
var formatted = ("0" + (date.getMonth() + 1)).slice(-2) + "/" + ("0" + date.getDate()).slice(-2) + "/" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes() + ":" + "0" + date.getSeconds();
return formatted;
}
}
but this function returns
//07/19/2013 11:38
instead of //7/19/2013 11:38:07 AM which is desired result.Please help me solving this problem. Thank You very much. Also , I need to show Am or PM that is compulsory
Try this:
function ParseDateToLocale(jsonDate) {
var date = new Date(parseInt(jsonDate.substr(6)));
var myDate = new Date(date);
var formatted = myDate.toLocaleString();
return formatted;
}
See it working here: http://jsfiddle.net/2ft3A/.
Try this one, this will help you,
function ParseDate(jsonDate) {
var date = new Date(parseInt(jsonDate.substr(6)));
var merd='';
if(date.getHours()>=12)
{
merd='PM';
}
else
{
merd='AM';
}
var formatted = ("0" + (date.getMonth() + 1)).slice(-2) + "/" + ("0" + date.getDate()).slice(-2) + "/" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes() + ":" + "0" + date.getSeconds()+ " " + merd;
return formatted;
}
dateObject.toLocaleTimeString(); (OR) date.getHours() will return 0-24hrs. Base on that value you can append AM or PM

Combine date and time string into single date with javascript

I have a datepicker returning a date string, and a timepicker returning just a time string.
How should I combine those into a single javascript Date?
I thought I found a solution in Date.js. The examples shows an at( )-method, but I can't find it in the library...
You can configure your date picker to return format like YYYY-mm-dd (or any format that Date.parse supports) and you could build a string in timepicker like:
var dateStringFromDP = '2013-05-16';
$('#timepicker').timepicker().on('changeTime.timepicker', function(e) {
var timeString = e.time.hour + ':' + e.time.minute + ':00';
var dateObj = new Date(datestringFromDP + ' ' + timeString);
});
javascript Date object takes a string as the constructor param
Combine date and time to string like this:
1997-07-16T19:20:15
Then you can parse it like this:
Date.parse('1997-07-16T19:20:15');
You could also use moment.js or something similar.
For plain JavaScript:
combineDateAndTime = function(date, time) {
timeString = time.getHours() + ':' + time.getMinutes() + ':00';
var year = date.getFullYear();
var month = date.getMonth() + 1; // Jan is 0, dec is 11
var day = date.getDate();
var dateString = '' + year + '-' + month + '-' + day;
var combined = new Date(dateString + ' ' + timeString);
return combined;
};
You can concatenate the date and time, and then use moment to get the datetime
const date = '2018-12-24';
const time = '23:59:59';
const dateTime = moment(`${date} ${time}`, 'YYYY-MM-DD HH:mm:ss').format();
Boateng's example fails in cases where time consisted of hours, minutes, days or months that ranged from values 0-9 as getDate(), getMonth() etc... will return 1 digit in these cases and the time string will fail and an invalid date is returned:
function CombineDateAndTime(date, time) {
const mins = ("0"+ time.getMinutes()).slice(-2);
const hours = ("0"+ time.getHours()).slice(-2);
const timeString = hours + ":" + mins + ":00";
const year = date.getFullYear();
const month = ("0" + (date.getMonth() + 1)).slice(-2);
const day = ("0" + date.getDate()).slice(-2);
const dateString = "" + year + "-" + month + "-" + day;
const datec = dateString + "T" + timeString;
return new Date(datec);
};
Unfortunately do not have enough rep to comment
David's example with slight modifications:
function CombineDateAndTime(date, time) {
var timeString = time.getHours() + ':' + time.getMinutes() + ':00';
var ampm = time.getHours() >= 12 ? 'PM' : 'AM';
var year = date.getFullYear();
var month = date.getMonth() + 1; // Jan is 0, dec is 11
var day = date.getDate();
var dateString = '' + year + '-' + month + '-' + day;
var datec = dateString + 'T' + timeString;
var combined = new Date(datec);
return combined;
};
Concate date and time with moment JS which also works on firefox,
let d1 = moment().format('MM/DD/YYYY');
let dateTimeOpen = moment(d1 + ' ' + model.openingTime).format('YYYY-MM-DD HH:mm:ss');
let dateTimeClose = moment(d1 + ' ' + model.closingTime).format('YYYY-MM-DD HH:mm:ss');
const date = "2022-12-27";
const time = "16:26:42";
new Date(`${date}T${time});
output
Date Tue Dec 27 2022 16:26:42 GMT+0100 (Central European Standard Time)

convert string into datetime object in javascript

I have to send Date object for current date to my back end from javascript
What I am doing is
var currentDate = new Date();
var dateString = currentDate.getMonth() + "-"
+ currentDate.getDate() + "-" + currentDate.getFullYear() + " "
+ currentDate.getHours() + ":" + currentDate.getMinutes() + ":"
+ currentDate.getSeconds();
var newDate = new Date(Date.parse(dateString));
But it is saying Invalid Date to newDate.
I have to send 3-10-2013 6:10:25 PM as datetime object to backend.
var currentDate = new Date(),
utcYear = currentDate.getUTCFullYear(),
utcMonth = ('0' + currenctDate.getUTCMonth()).slice(-2),
utcDay = ('0' + currentDate.getUTCDate()).slice(-2),
fullDateString = utcMonth.toString() + '/' + utcDay.toString() + '/' + utcYear.toString();
Same principle if you want to get the time part as well.
Instead of putting - in between the month/date and date/year, just put spaces.
var currentDate = new Date(),
dateString = currentDate.getMonth() + " " +
currentDate.getDate() + " " +
currentDate.getFullYear() + " " +
currentDate.getHours() + ":" +
currentDate.getMinutes() + ":" +
currentDate.getSeconds(),
newDate = new Date(dateString);
console.log(newDate)

Categories

Resources