My string format is: M/d/yyyy h:m:s aa
Now, I want to change it in yyyy-MM-ddTHH:mm:ss format.
How can I change it in this format. Please tell me appropriate solution
The method getConvertedDate(String), will do a plain text parsing for conversion.
private String getConvertedDate(String inputDate) {
// extract and adjust Month
int index = inputDate.indexOf('/');
String month = inputDate.substring(0, index);
if (month.length() < 2) {
month = "0" + month;
}
// extract and adjust Day
inputDate = inputDate.substring(index + 1);
index = inputDate.indexOf('/');
String day = inputDate.substring(0, index);
if (day.length() < 2) {
day = "0" + day;
}
// extract Year
inputDate = inputDate.substring(index + 1);
index = inputDate.indexOf(' ');
String year = inputDate.substring(0, index);
// extract Hour
inputDate = inputDate.substring(index + 1);
index = inputDate.indexOf(':');
String hour = inputDate.substring(0, index);
// extract and adjust Minute
inputDate = inputDate.substring(index + 1);
index = inputDate.indexOf(':');
String minute = inputDate.substring(0, index);
if (minute.length() < 2) {
minute = "0" + minute;
}
// extract and adjust Second
inputDate = inputDate.substring(index + 1);
index = inputDate.indexOf(' ');
String second = inputDate.substring(0, index);
if (second.length() < 2) {
second = "0" + second;
}
// extract AM/PM marker
// adjust hour, +12 for PM
inputDate = inputDate.substring(index + 1);
String am_pm_marker = inputDate.substring(0);
if (am_pm_marker.equalsIgnoreCase("pm")) {
int hourValue = 0;
try {
hourValue = Integer.parseInt(hour);
} catch (Exception e) {
}
hourValue += 12;
hour = "" + hourValue;
if (hour.length() < 2) {
hour = "0" + hour;
}
} else {
if (hour.length() < 2) {
hour = "0" + hour;
}
}
String outputDate = year + "-" + month + "-" + day;
outputDate += "T" + hour + ":" + minute + ":" + second;
return outputDate;
}
Sample input and output:
String input = "04/01/2012 9:55:47 pm";
System.out.println("Output: " + getConvertedDate(input));
// Output: 2012-04-01T21:55:47
Date date = (Date)new SimpleDateFormat("M/d/yyyy h:m:s aa").parse(your_string_date);
String finalFormat = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss").format(date)
Basically the first SimpleDateFormat recognizes your original format and parses it into a Date. Then the second one formats the date object to what you need.
I don't have jdk around to test here, but it should work.
Check this links for format syntax in case something doesn't work:
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
Related
I'm making a PWA on angular 8 / ionic 5. Users can create events and have them listed on a feed page. Problem is, that the date and the time of each event does not get displayed and gives the error "NaN" on iphones/iOS devices. Both date and time get their information from start_at which is the time in the format of "hh:mm:ss".
Following code shows how we receive the response data from our MySQL php laravel server for listing the events:
getTodos() {
console.log("arrived to gettodos");
var id = this.userInfo.id
this.todoService.getTodos('', '', '', id, false).subscribe(res => {
console.log("res", res);
console.log("frimes", res['frimes']);
// debugger;
// console.log(res);
if (res['code'] === 200) {
// console.log(res['data']);
const userFrimes: any[] = res['frimes'];
this.todos = [] as any[];
console.log(userFrimes);
if (userFrimes && userFrimes.length > 0) {
userFrimes.forEach(uf => {
var timeofFrime = this.formatAMPM(uf.start_at);
if (!this.todoService.isFrimeExpired(uf.start_at)) {
this.todos.push({
owner: this.userInfo.username,
title: uf.title,
message: uf.description,
date: uf.start_at,
time: timeofFrime,
max: uf.max,
guests: uf.member.length, //uf.guests == null ? 0 : uf.guests,
frime_id: uf.id,
status: uf.status,
user_id: uf.user_id
});
}
});
}
} else if (res['code'] === 205) {
} else if (res['code'] === 401) {
}
}, err => {
//this.errorMessage = err.message;
console.log(err);
});
}
here you can see that the properties date and time are being fetched for the formatAMPM() function and changed to the AM/PM date format.
formatAMPM(d) {
let dd = d + " UTC";
let date = new Date(dd);
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
var min = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + min + ' ' + ampm;
return strTime;
}
here the final date string gets displayed in the pipe fields where it shows the "NaN" error on ios.
the error itself says:
ERROR Error: InvalidPipeArgument: 'Unable to convert "2021-05-19 17:15:38" into a date' for pipe 'Re'.
what does 'Re' mean btw?
<ion-col size="3" class="date-wrapper">
<h3 class="notification-date">
{{ item.date | date: "shortDate" }}
</h3>
<h3 class="notification-date">
{{ item.time | date: "HH:mm" }}
</h3>
<h3 class="notification-date">{{ item.guests + '/' + item.max }}</h3>
</ion-col>
hope you can help me fixing this, because this is giving me soooo many headachse lately...
thanks in advance!
ok i have fixed it by adding this line of code:
d = d.replace(" ", "T");
the date came in a format like dd-MM-yyyy HH:mm:ss and i needed to add the "T" so it is like dd-MM-yyyyTHH:mm:ss
formatAMPM(d) {
d = d.replace(" ", "T");
let dd = d + " UTC";
let date = new Date(dd);
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
var min = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + min + ' ' + ampm;
return strTime;
}
The amibroker function datenum() returns an array with dates represented in numbers. How to convert this array into the string equivalent?
DateNum
I have this function below which almost accomplishes this task except that only year 2000 and after is supported. How to fix it such that dates before year 2000 can be supported?
/*
Function changes DateNum ex:1040928 en String ddmmyyyy ex:28/09/2004 ( only > 2000 year )
*/
function sDate( nDate )
{
string = StrFormat( "%0.9g", nDate );
//extract string part
aa = StrLeft( string, 3 );
mm = StrMid( string, 3, 2 );
dd = StrRight( string, 2 );
//transform year en num
aa1 = StrToNum( aa ) + 1900; // ONLY CORRECT AFTER 2000
yyyy = NumToStr( aa1, 1, False );
result = yyyy + "-" + mm + "-" + dd;
return result;
}
Change line
string = StrFormat( "%0.9g", nDate );
to
string = StrFormat( "%07.07g", nDate );
You can convert datenum to string easily using built-in afl functions, this is the code to use:
DateNumberArray = DateTimeConvert( 2, DateNum() );
for ( i = 0; i < BarCount; i++ )
{
_TRACE( DateTimeToStr( DateNumberArray [i] ) );
}
2 is a code for converting from DateNum, see DateTimeConvert documentation.
I'm trying to enable only Thursdays and Sundays but also disable some specific Sundays or Thursdays.
I'm trying with this function but it's not working yet:
<script>
var unavailableDates = ["2013-03-31", "2013-03-24"];
function disabledays(date) {
ymd = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
if ($.inArray(ymd, unavailableDates) == 0) {
return [false, "", "Unavailable"]
} else {
//Show only sundays and thuersdays
var day = date.getDay();
return [(day == 0 || day == 4)];
}
$('#txtDate').datepicker({
beforeShowDay: disabledays
})
</script>
Two problems:
The code that builds a date string does not add a 0 to the month portion. You could change your unavailableDates array.
You need to check the return value of $.indexOf to see if it's >= 0 instead of just equal to zero.
With both changes:
var unavailableDates = ["2013-3-31", "2013-3-24"];
function disabledays(date) {
var ymd = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
if ($.inArray(ymd, unavailableDates) >= 0) {
return [false, "", "Unavailable"];
} else {
//Show only sundays and thuersdays
var day = date.getDay();
return [(day == 0 || day == 4)];
}
}
$('#txtDate').datepicker({
beforeShowDay: disabledays
});
Example: http://jsfiddle.net/XJKbV/
Hi I have the code to separate hour,min,sec
Now i have to convert it in to seconds.and nsnumber
NSRange range = [string rangeOfString:#":"];
NSString *hour = [string substringToIndex:range.location];
NSLog(#"time %#",hour);
NSRange range1= NSMakeRange(2,2);
NSString *min = [string substringWithRange:range1];
NSLog(#"time %#",min);
NSRange range2 = NSMakeRange(5,2);
NSString *sec = [string substringWithRange:range2];
NSLog(#"time %#",sec);
If you want to find out how many seconds the hours, minutes and seconds total, you can do something like this:
- (NSNumber *)secondsForTimeString:(NSString *)string {
NSArray *components = [string componentsSeparatedByString:#":"];
NSInteger hours = [[components objectAtIndex:0] integerValue];
NSInteger minutes = [[components objectAtIndex:1] integerValue];
NSInteger seconds = [[components objectAtIndex:2] integerValue];
return [NSNumber numberWithInteger:(hours * 60 * 60) + (minutes * 60) + seconds];
}
Just an alternative if you have to handle both "HH:mm:ss" and "mm:ss"
extension String {
/**
Converts a string of format HH:mm:ss into seconds
### Expected string format ###
````
HH:mm:ss or mm:ss
````
### Usage ###
````
let string = "1:10:02"
let seconds = string.inSeconds // Output: 4202
````
- Returns: Seconds in Int or if conversion is impossible, 0
*/
var inSeconds : Int {
var total = 0
let secondRatio = [1, 60, 3600] // ss:mm:HH
for (i, item) in self.components(separatedBy: ":").reversed().enumerated() {
if i >= secondRatio.count { break }
total = total + (Int(item) ?? 0) * secondRatio[i]
}
return total
}
}
Swift 4 - improved from #Beslan Tularov's answer.
extension String{
var integer: Int {
return Int(self) ?? 0
}
var secondFromString : Int{
var components: Array = self.components(separatedBy: ":")
let hours = components[0].integer
let minutes = components[1].integer
let seconds = components[2].integer
return Int((hours * 60 * 60) + (minutes * 60) + seconds)
}
}
Usage
let xyz = "00:44:22".secondFromString
//result : 2662
You can also try like this:
extension String{
//format hh:mm:ss or hh:mm or HH:mm
var secondFromString : Int{
var n = 3600
return self.components(separatedBy: ":").reduce(0) {
defer { n /= 60 }
return $0 + (Int($1) ?? 0) * n
}
}
}
var result = "00:44:22".secondFromString //2662
result = "00:44".secondFromString //2640
result = "01:44".secondFromString //6240
result = "999:10".secondFromString //3597000
result = "02:44".secondFromString //9840
result = "00:01".secondFromString //60
result = "00:01:01".secondFromString //61
result = "01:01:01".secondFromString //3661
result = "12".secondFromString //43200
result = "abcd".secondFromString //0
From what you've,
double totalSeconds = [hour doubleValue] * 60 * 60 + [min doubleValue] * 60 + [sec doubleValue];
NSNumber * seconds = [NSNumber numberWithDouble:totalSeconds];
The following is a String extension for converting a time string (HH:mm:ss) to seconds
extension String {
func secondsFromString (string: String) -> Int {
var components: Array = string.componentsSeparatedByString(":")
var hours = components[0].toInt()!
var minutes = components[1].toInt()!
var seconds = components[2].toInt()!
return Int((hours * 60 * 60) + (minutes * 60) + seconds)
}
}
how to use
var exampleString = String().secondsFromString("00:30:00")
You can use the following extension to do that (Swift 3):
extension String {
func numberOfSeconds() -> Int {
var components: Array = self.components(separatedBy: ":")
let hours = Int(components[0]) ?? 0
let minutes = Int(components[1]) ?? 0
let seconds = Int(components[2]) ?? 0
return (hours * 3600) + (minutes * 60) + seconds
}
}
And for example, use it like:
let seconds = "01:30:10".numberOfSeconds()
print("%# seconds", seconds)
Which will print:
3790 seconds
How to create/read/delete cookie in blackberry widget?
have same issue but trying out these codes:
function createCookie(name, value, days) {
eraseCookie(name);
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}