Need just time from this date time format [duplicate] - javascript

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 5 years ago.
I was looking for EDT time and got this in this format :
Wed Nov 01 2017 06:42:26 GMT+0530 (India Standard Time)
Although, I just want it like 6:42 AM to display !! I tried date time function
but doesnt help !!
Is it advisable to do this with any string function or will it give issue in future (I dont want any calculation on this )

Use moment.js format to work with date in JS.
moment("Wed Nov 01 2017 06:42:26 GMT+0530").format("hh:mm a")

You can use
var date = "Wed Nov 01 2017 06:42:26 GMT+0530";
var formattedDate = new Date(date);
var hours = formattedDate.getHours();
var minutes = formattedDate.getMinutes();
hours = (hours > 12) ? (hours - 12) : hours;
var period = (hours > 12) ? 'PM' : 'AM';
var time = hours + ':' + minutes + ' ' + period;
or you can also use moment.js, here is the details on 'format' function.
var time = moment(date).format("hh:mm A");

var date = new Date();
var hour = date.getHours();
var minutes = date.getMinutes();
var time = hour + ':' + minutes;
This would work.
Note: momentjs is great library for time manipulation, it is not good idea to include such a big library for small functions like this.

Related

Get Meridian from time in Javascript

I have following time "Mon Jun 22 03:45:24 PDT 2015" how can I get Meridian using Javascript.
I was doing this:
d= Mon Jun 22 03:45:24 PDT 2015;
var hours = d.getHours();
var meridiem = "AM";
if (d.getHours() > 12) {
hours = d.getHours() % 12;
if (hours == 2) {
hours = 12;
}
meridiem = "PM";
}
But its not working in IE 8.
you define
d= Mon Jun 22 03:45:24 PDT 2015;
actually it is nothing in javascript
some browser more intelligent some not, it's up to the browser behaviour
you have to tell javascript like that
function getCurrentTime() {
var currentTime;
// here we can give our date
var currentDate = new Date("Mon Jun 22 03:45:24 PDT 2015");
// OR we can define like that also for current date
// var currentDate = new Date();
var hour = currentDate.getHours();
var meridiem = hour >= 12 ? "PM" : "AM";
currentTime = ((hour + 11) % 12 + 1) + ":" + currentDate.getMinutes() + meridiem;
return currentTime;
}
We can get time in 12 hour format, including the meridian by using the Date.prototype.toLocaleTimeString() method with a US English argument which returns the time in AM/PM. Without the argument 'en-US' date will return the format it deems appropriate for your timezone.
From there we can utilise the slice method to get the last two characters of the timestamp using a negative index:
var d = new Date("Mon Jun 22 03:45:24 PDT 2015")
// US English uses 12-hour time with AM/PM
var timestamp = d.toLocaleTimeString('en-US');
// timestamp → "03:45:24 AM"
var meridian = timestamp.slice(-2);
// meridian → "AM"
One liner for brevity:
var meridian = new Date("Mon Jun 22 03:45:24 PDT 2015").toLocaleTimeString().slice(-2);
According to the documentation for JavaScript Date object here, there is no method for directly getting 12-hour hours and therefore no method for getting am/pm directly from the Date object.
You can get hours (24-hour format) which you can use to get 12-hour hours and am/pm. (You've already done it but I don't understand what you're trying to do in your code.)
This would be one way to do this.
This code is inspired by #tinka.
var d = new Date("Mon Jun 22 03:45:24 PDT 2015");
var h = (d.getHours() + 11) % 12 + 1; //Courtesy #tinka
var m = h > 12 ? 'pm' : 'am';
And you can always add methods to Date.prototype if you're gonna be using them repeatedly.
Date.prototype.getHours12 = function() {
return (this.getHours() + 11) % 12 + 1; // edited.
}
Date.prototype.getMeridiem = function() {
return this.getHours() > 12 ? 'pm' : 'am';
}
It should work on all platforms.
With Date object:
getMeridiem(date: Date) {
return date.toLocaleTimeString().split(' ')[1];
}

Set Date Time to Jquery date time picker

I have date in Javascript
Sun Feb 15 2015 08:02:00 GMT+0200 (EET)
how I can to set in format 'dd/mm/yyyy hh:mm:ss' into datetime picker?
If I set like this:
dateStart
Sun Feb 15 2015 08:02:00 GMT+0200 (EET)
$('#dateTimeStart').datetimepicker('setDate', dateStart);
Error parsing the date/time string: Missing number at position 10
date/time string = 02-15-2015 08:02:00
timeFormat = HH:mm
dateFormat = mm-dd-yyyy
$('#dateTimeStart').datetimepicker({
dateFormat: 'yy-dd-mm'
timeFormat: "hh:mm:ss"
});
You have to format date that you have. You can do it with help of function that you can grab here.
Usage:
<script>
document.write($.format.date("Sun Feb 15 2015 08:02:00", "dd/mm/yyyy hh:mm:ss"));
</script>
It's small and really nice solution that can help you to resolve your issue.
You're looking for a format like
jQuery('#dateTimeStart').datetimepicker({
format:'d/m/Y H:i:s'
});
According to the DateTimePicker documentation at http://xdsoft.net/jqplugins/datetimepicker/, the 'format' string is based on the PHP date format strings, which you can read up on at http://php.net/manual/en/function.date.php. Note in particular they use just one letter to represent multiple numbers (e.g. 'd' instead of 'dd')
use below javascript code to change formate
var date = new Date('Sun Feb 15 2015 08:02:00 GMT+0200');
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var fulldate = day+'/'+(month+1)+'/'+year+' '+hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
see working copy of fiddle
you can create function which return date in format
function convertdate(param){
var date = new Date(param);
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
return fulldate = day+'/'+(month+1)+'/'+year+' '+hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
}
alert(convertdate('Sun Feb 15 2015 08:02:00 GMT+0200'));
I change format of date from server in this : '02/15/2015 08:02:00 AM'
and then I parse this string and create new date:
var dateString ='02/15/2015 08:02:00 AM';
var dateStart = new Date(Date.parse(dateString, "mm/dd/yyyy hh:mm:ss"));
$('#dateTimeStart').datetimepicker('setDate', dateStart);

How to make JS date respect local timezone?

I have the follow function that properly returns the date in the format required, but the value returned isn't respecting the local timezone. In this case, its 4 hours off. What would I need to modify in this function to make it add the proper offsets based on the users location?
Thanks!
function date_str(seconds) {
var dt = new Date(1970, 0, 1);
dt.setSeconds(seconds);
console.log(dt);
var month = dt.getMonth() + 1;
var date = dt.getDate();
var year = dt.getFullYear();
var hours = dt.getHours();
var minutes = dt.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
return month + '/' + date + '/' + year + ', ' + hours + ':' + minutes + ' ' + ampm;
}
Edit: Passing unix time to function 1396450616.505 which converts to Wed, 02 Apr 2014 14:56:56 GMT which returns Sent at 4/2/2014, 2:56 PM from the function itself. The time here is 10:56 AM EST.
Assuming that seconds is a unix epoch (UTC), you should just use
function date_str(seconds) {
var dt = new Date(seconds*1000);
console.log(dt);
…
instead. The get…() methods will respect the local timezone. If you don't want that, you should use the getUTC…() equivalents.

Convert UTC datetime to local datetime

I tried many times to convert utc datetime to local datetime,and I have failed. My utc datetime format is
Fri Mar 8 23:12:27 UTC+0200 2013
Also my JavaScript code is
var time = Date(param_time);//param_time is /Date(1362866006646)/
And then time is being Sun Mar 10 00:21:54 UTC+0200 2013 I need to datetime as 2008-01-28T20:24:17Z because I will convert local datetime to pretty datetime.
http://ejohn.org/files/pretty.js
How can I do this ? I looked at many questions on stackoverflow but no one does it work. Thank you.
In order to format your Date correctly use toISOString():
var time = param_time.toISOString();
Note that param_time needs to be a valid Date object.
References
MDN: Date (sections: Syntax, Example: ISO 8601 formatted dates)
I rarely use javascript and all this date time conversion are mystery to me as well, javascript is a client side technology and all this "UTC" phrases means nothing (at least to me), as all the kind of getUTC...()/setUTC...() functions works in local time, the same is goes for all Date.to...String() functions, even the new Date() (that due to the docs) s'd be initialized in UTC, also give a local time.
However, if you have a (correct) date in UTC and wish to convert it to current (client side) local time, then you need getTimezoneOffset(), or shortly:
function UTCToLocalTime(d) {
var timeOffset = -((new Date()).getTimezoneOffset()/60);
d.setHours(d.getHours() + timeOffset);
return d;
}
var time = new Date(Date.parse('Fri Mar 8 23:12:27 UTC+0200 2013'));
alert(UTCToLocalTime(time)); // Sat Mar 9 01:12:27 UTC+0200 2013
//p.s. or...
function UTCToLocalTime2(d)
{
return new Date(d.toString().replace(/UTC.*/g,"") + d.getYear());
}
var timezone = "UTC+01:30";
var start = new Date();
if(timezone != "UTC"){
timezone = timezone.replace(/UTC/g,"");
znak = timezone.charAt(0);
timezone = timezone.replace(/[+|-]/g,"");
timezone = timezone.split(":");
//var start = new Date(start.toString() + " " + timezone);e.
//alert(start.toString());
if(znak == "+") start = new Date(start.getTime() + (timezone[0]*60*60000 + timezone[1] * 60000) );
if(znak == "-") start = new Date(start.getTime() - (timezone[0]*60*60000 + timezone[1] * 60000) );
}
var hours = start.getUTCHours();
var minutes = start.getUTCMinutes();
var seconds = start.getUTCSeconds();
var day = 10;
var month = 04;
var year = 2015;
var dateUtc = Date.UTC(year, month - 1, day + 1, 0, 0, 0);
> 1428710400000
var toDate = new Date(dateUtc);
> Fri Apr 10 2015 21:00:00 GMT-0300 (Hora oficial do Brasil)

javascript date & time join

I have two date variable separately like following
startDate is a Date instance with the value Tue Jul 17 2012 00:00:00 GMT+0530 (IST)
startTime is a String with the value "11:30 AM"
Now what I need is join of both above date & time, as a Date.
startDateTime = Tue Jul 17 2012 11:30:00 GMT+0530 (IST)
I tried
new Date(startDate + " " + startDate) but outputting invalid date.
Also tried the way shown on this post. But still not working.
You can readily parse startTime if it's in a clearly-defined format, then use setHours and setMinutes: Live example | source
var startDateTime;
var parts = /^(\d+):(\d+) (AM|PM)$/.exec(startTime);
if (parts) {
hours = parseInt(parts[1], 10);
minutes = parseInt(parts[2], 10);
if (parts[3] === "PM" && hours !== 12) {
hours += 12;
}
else if (parts[3] === "AM" && hours === 12) {
hours = 0;
}
if (!isNaN(hours) && !isNaN(minutes)) {
startDateTime = new Date(startDate.getTime());
startDateTime.setHours(hours);
startDateTime.setMinutes(minutes);
}
}
...or something along those lines.
Note that key to this is the fact you've said startDate is a Date instance. The above assumes we're working within the timezone of the JavaScript environment, not across zones. If you were starting with a date string instead, and that string specified a timezone other than the JavaScript environment's timezone, which you were then converting into a Date via new Date("Tues Jul...."), then you'd have to be sure to adjust the resulting Date to use either the local time of the environment, or UTC; if you adjusted it to be UTC, you'd use setUTCHours and setUTCSeconds above instead of setHours and setSeconds. Again, this is only an issue if your starting point is a date string, and that string specifies a timezone different from the timezone in which the code above is running.
You can do This:
var theDate = new Date("Tue Jul 17 2012 00:00:00 GMT+0530 (IST)");
var theTime = "11:30 AM";
var hours = theTime .substr(0,2);
var minutes = theTime .substr(3,2);
var amOrPm = theTime .substr(6,2);
if (hours < 12 && "PM" == amOrPm) {
hours = +hours + 12;
}
theDate.setHours(hours);
theDate.setMinutes(minutes);
Try
new Date(startDate.toDateString() + " " + startTime)
This combines the date string from your Date object with the time string, and should give you a valid date. Note that this ignores the timezone you initially worked with, you might need to add " GMT+0530" again.
However, because your date string is already timezone-biased (Jul 16 2012, 20:30:00 UTC) it might be better to add them together, i.e. like new Date(+startDate + milliseconds):
var startDate = new Date("Tue Jul 17 2012 00:00:00 GMT+0530");
var startTime = "11:30 AM";
return new Date(+startDate + +new Date("1 1 1970 "+startTime))

Categories